我正在编写一个订阅清除查询,该查询应选择所有已取消的订阅,这些订阅的用户没有任何其他活动订阅(该应用程序允许每个用户进行多个订阅)。
我从这里开始:
SELECT * FROM subscriptions s WHERE status = 'canceled' AND (SELECT COUNT(*) FROM subscriptions s2 where s2.user_id = s.user_id AND status = 'active') = 0;
但是,我觉得必须有一种更简单/更直接/更高效的方式。
答案 0 :(得分:3)
这里不存在可能更直观:
SELECT * FROM subscriptions s WHERE status = 'canceled'
AND NOT EXISTS
(SELECT id FROM subscriptions s2 where s2.user_id = s.user_id AND status = 'active');
您还可以在此处使用LEFT JOIN:
SELECT *
FROM
subscriptions s LEFT OUTER JOIN
subscriptions s2 ON s.USER_ID = s2.USER_ID AND s2.status='active'
WHERE status = 'canceled' AND s2.id IS NULL