返回false表示空表不存在

时间:2012-07-18 18:29:32

标签: mysql subquery not-exists

我有2个表的SELECT查询没有返回任何结果,我不知道为什么不是。这是不返回任何行的查询:

SELECT b.name, b.description, b.badge_id 
FROM badges AS b 
WHERE b.type = 'have' AND b.brand_id = 'zTR7wH5FMl' AND ISNULL(b.series_id) AND b.amount <= 89 
AND NOT EXISTS (SELECT date_earned 
                FROM users_badges AS ub 
                WHERE ub.user_id = 'fMcBBx' AND ub.badge_id = b.badge_id)

如果我在最后取消AND NOT EXISTS条款以检查他们是否已经获得徽章,我会收到这些结果:

name            description                                             badge_id
Baker's Dozen   Add 13 items to your Johnny Cupcakes shelf.             sdfKHJkun7
Cupcaker        Have 82 items on your Johnny Cupcakes shelf.            4MeoheBdik
Freshly Baked   Have your first item on your Johnny Cupcakes shelf...   kdJGH98NdI

这正是我期望得到的。 AND NOT EXISTS检查是唯一的区别。 users_badges表中还没有数据,所以我不明白为什么它会返回false。在我看来,它将无法返回虚假。为什么它会使整个查询无效?

2 个答案:

答案 0 :(得分:1)

在表中添加一行似乎解决了这个问题。我想如果表是空的,SQL甚至不检查EXISTS条件并且总是返回false,因为表中的行不存在。

答案 1 :(得分:1)

尝试将NOT EXISTS替换为LEFT JOIN / IS NULL

SELECT    b.name, b.description, b.badge_id 
FROM      badges b 
LEFT JOIN user_badges ub ON b.badge_id = ub.badge_id AND ub.user_id = 'fMcBBx'
WHERE     b.type = 'have' AND 
          b.brand_id = 'zTR7wH5FMl' AND 
          b.amount <= 89 AND
          b.series_id IS NULL AND 
          ub.badge_id IS NULL