假设我有 2 个用于用户和任务的表。任务中有 user_id 和状态,状态可能值为“完成”和“未完成”。现在我想检索甚至没有完成一项任务的用户。最粗略的方法是首先找到至少完成 1 个任务的用户并运行“不在”查询。
没有“in”子查询的任何更好的方法来实现这一点。请注意,数据集很大,我不能长时间锁定任务表!
SELECT *
FROM users u
WHERE NOT EXISTS (
SELECT * FROM tasks t
WHERE t.user_id = u.user_id
AND t.status = 'complete'
);
当task.user_id
不能包含 NULL(即有NOT NULL
约束)时,LEFT JOIN
withIS NULL
是您的最佳选择:
SELECT user.* FROM user
LEFT JOIN task ON (task.user_id = user.id AND task.status = 'complete')
WHERE task.user_id IS NULL
试试下面这个查询将列出已完成甚至 1 个任务或超过 1 个任务的用户
SELECT u.*,
COUNT( CASE WHEN t.`status`= 'Completed' THEN t.`status` END ) AS completed ,
COUNT( CASE WHEN t.`status`= 'Not completed' THEN t.`status` END ) AS Not_completed
FROM `user` u
LEFT JOIN `task` t ON (u.id =t.user_id)
GROUP BY t.user_id HAVING completed >0
这将列出那些甚至没有完成一项任务的用户
SELECT u.*,
COUNT( CASE WHEN t.`status`= 'Completed' THEN t.`status` END ) AS completed ,
COUNT( CASE WHEN t.`status`= 'Not completed' THEN t.`status` END ) AS Not_completed
FROM `user` u
LEFT JOIN `task` t ON (u.id =t.user_id)
GROUP BY t.user_id HAVING completed = 0