Tenga en cuenta que una consulta no se ejecuta de forma imperativa. La consulta que escribió puede ejecutarse en varios subprocesos y, por lo tanto, un operador de cortocircuito en la cláusula where no generaría un solo resultado.
En su lugar, utilice el LIMIT
cláusula para devolver solo la primera fila.
SELECT * FROM quantitycache
WHERE bookstore_id = 1 OR city_id = 1 OR country_id = 1
ORDER BY bookstore_id IS NULL ASC,
city_id IS NULL ASC,
country_id IS NULL ASC
LIMIT 1;
Para obtener la mejor coincidencia para todos los libros en un conjunto de resultados, guarde los resultados en una tabla temporal, encuentre el mejor resultado y luego devuelva los campos interesantes.
CREATE TEMPORARY TABLE results (id int, book_id int, match_rank int);
INSERT INTO results (id, book_id, match_rank)
SELECT id, book_id,
-- this assumes that lower numbers are better
CASE WHEN Bookstore_ID is not null then 1
WHEN City_ID is not null then 2
ELSE 3 END as match_rank
FROM quantitycache
WHERE bookstore_id = 1 OR city_id = 1 OR country_id = 1;
Select *
from (
select book_id, MIN(match_rank) as best_rank
from results
group by book_id
) as r
inner join results as rid
on r.book_id = rid.book_id
and rid.match_rank = r.best_rank
inner join quantitycache as q on q.id = rid.id;
DROP TABLE results;