假设我有2个表供用户使用任务。有user_id&具有可能值“完成”的状态的任务状态& “不完整”。 现在我想检索甚至没有完成任务的用户。 最粗略的方法是首先找到至少有一个完整任务并运行“不在”查询的用户。
没有“in”子查询的任何更好的方法来实现这一点。请注意,数据集很大,我无法长时间锁定任务表!
答案 0 :(得分:1)
SELECT *
FROM users u
WHERE NOT EXISTS (
SELECT * FROM tasks t
WHERE t.user_id = u.user_id
AND t.status = 'complete'
);
答案 1 :(得分:1)
如果task.user_id
不能包含NULL(即NOT NULL
约束),LEFT JOIN
IS NULL
就是best choice:
SELECT user.* FROM user
LEFT JOIN task ON (task.user_id = user.id AND task.status = 'complete')
WHERE task.user_id IS NULL
答案 2 :(得分:0)
尝试以下查询将列出已完成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