我要选择没有任何订单或没有任何“ PAID”订单的用户:
SELECT "users".*
FROM "users"
LEFT OUTER JOIN orders ON orders.user_id=users.id
WHERE (NOT (orders.state = 'paid'))
这只会返回尚未支付订单的用户,而忽略没有订单的用户。
我该如何纠正?
答案 0 :(得分:1)
这是逻辑:
SELECT u.*
FROM "users" u LEFT JOIN
orders o
ON o.user_id = u.id AND o.state = 'paid' -- match on "paid"
WHERE o.user_id IS NULL; -- return without a match
使用NOT EXISTS
可能会更好地理解这一点:
SELECT u.*
FROM "users" u
WHERE NOT EXISTS (SELECT 1 -- the following does not exist
FROM orders o
WHERE o.user_id = u.id AND -- match on the user
o.state = 'paid' -- match paid state
);