NOT EXISTS on empty table returning false
-
21-06-2021 - |
質問
I have a SELECT query across 2 tables that isn't returning any results and I have no idea why it isn't. This is the query that doesn't return any rows:
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)
If I just take off the AND NOT EXISTS clause at the end to check that they haven't already earned the badge I get these results back:
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
Which is exactly what I expect to get. The AND NOT EXISTS check is the only difference. There is no data in the users_badges table yet, so I don't see why it would be returning false. It seems to me that it would be incapable of returning false. Why would it be invalidating the entire query?
解決
Adding a row to the table seems to have solved it. I guess if the table is empty SQL doesn't even check the EXISTS condition and always returns false because there is no way the row could exist in the table.
他のヒント
Try replacing the NOT EXISTS
with a 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