SQL:选择其他表中不存在的位置

时间:2019-02-09 20:19:47

标签: mysql sql join mysqli

我在每个表中都有相同的名称,但是即使确切的名称在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`

1 个答案:

答案 0 :(得分:2)

您的问题与您使用ANDOR运算符的方式有关: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 
    )