我在每个表中都有相同的名称,但是即使确切的名称在Ingredients_master表中,它仍从配料表中选择它。有什么想法吗?
SELECT
`ingredients`.`id`,
`ingredients`.`name`
FROM
`ingredients`
WHERE
`ingredients`.`name` LIKE '%makers%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%jack%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%hennesey%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%bourbon%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%RYE%' ESCAPE '!'
AND NOT EXISTS (
SELECT * FROM ingredients_master WHERE ingredients.NAME = ingredients_master.NAME
)
GROUP BY
`ingredients`.`name`
答案 0 :(得分:2)
您的问题与您使用AND
和OR
运算符的方式有关:AND
具有比OR
更高的优先级,因此:
WHERE
`ingredients`.`name` LIKE '%makers%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%jack%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%hennesey%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%bourbon%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%RYE%' ESCAPE '!'
AND NOT EXISTS (
SELECT * FROM ingredients_master WHERE ingredients.NAME = ingredients_master.NAME
)
实际上等同于:
WHERE
`ingredients`.`name` LIKE '%makers%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%jack%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%hennesey%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%bourbon%' ESCAPE '!'
OR (
`ingredients`.`name` LIKE '%RYE%' ESCAPE '!'
AND NOT EXISTS (
SELECT * FROM ingredients_master WHERE ingredients.NAME = ingredients_master.NAME
)
)
因此,如果第一个OR
条件中的任何一个为true,则结果为true,而与NOT EXIST
条件的结果无关。
您可能想要:
WHERE
(
`ingredients`.`name` LIKE '%makers%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%jack%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%hennesey%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%bourbon%' ESCAPE '!'
OR `ingredients`.`name` LIKE '%RYE%' ESCAPE '!'
)
AND NOT EXISTS (
SELECT * FROM ingredients_master WHERE ingredients.NAME = ingredients_master.NAME
)