返回其他表中不存在的记录子集

r6hnlfcb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(354)

我有一个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;
a5g8bdjr

a5g8bdjr1#

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

相关问题