我有这个SQL查询,可以返回整个集合:
SELECT s.id, s.status, s.created_at
FROM scores s
WHERE s.account_id IN (
SELECT a.id
FROM accounts a
WHERE a.status = 'ACTIVE' AND a.created_at >= DATE(NOW()) - 3 AND a.tool = 'GLR'
) ORDER BY s.created_at ASC;
...但是现在我想要一个子集:account
中的所有记录在score
中没有任何记录。
我已经尝试过这些,但是到目前为止还没有运气O:)
--- Using LEFT JOIN
SELECT s.account_id, s.status, s.created_at
FROM scores s
LEFT JOIN accounts a ON s.account_id = a.id
AND a.status = 'ACTIVE'
AND a.created_at >= DATE(NOW()) - 3
AND a.tool = 'GLR'
WHERE s.account_id IS NULL ORDER BY s.created_at ASC;
--- Using EXISTS / NOT EXISTS
SELECT s.account_id, s.status, s.created_at
FROM scores s
WHERE NOT EXISTS (
SELECT 1 FROM accounts a
WHERE s.account_id = a.id
AND a.status = 'ACTIVE'
AND a.created_at >= DATE(NOW()) - 3
AND a.tool = 'GLR'
) ORDER BY s.created_at ASC;
答案 0 :(得分:2)
SELECT a.* FROM accounts a LEFT JOIN scores s ON s.account_id = a.id
WHERE a.status = 'ACTIVE' AND a.created_at >= DATE(NOW()) - 3 AND a.tool = 'GLR'
AND s.account_id IS NULL