MySQL排除和要求

时间:2013-01-18 14:56:19

标签: mysql sql left-join

我想将此问题转换为查询。 猜测应该是三个leftjoin和两个选择

exercises
+-----+---------+
|  id | require | 
+-----+---------+
|  1  |         |
|  2  |    1    |
|  3  |    2    |
|  4  |    3    |
|  5  |         |
|  6  |    5    |
|  7  |         |
+-----+---------+

done
+-----+
|  id |
+-----+
|  1  |
|  2  |
+-----+

完成了第一和第二次练习,我现在可以做哪些练习? 解决方案:3,5,7

我的逻辑过程,一步一步:
(全部) - 选择(必填 - 完成) - (完成)
(1,2,3,4,5,6,7) - 选择((1,2,3,5) - (1,2)) - (1,2)
(1,2,3,4,5,6,7) - 选择(3,5) - (1,2)
(1,2,3,4,5,6,7) - (4,6) - (1,2)
(3,5,7)

如何编写查询?

4 个答案:

答案 0 :(得分:1)

select id 
from exercises
where require in (select id from done)
   or require is null
minus
select id from done;

你的设置是:“需要完成或没有要求的练习,执行那些”。

更新:没有减号(可能让你害怕):

select id 
from exercises
where (require in (select id from done)  or require is null)
   and id not in  (select id from done);

答案 1 :(得分:1)

这是一种做法。

SELECT * FROM `exercises`
WHERE `id` NOT IN (SELECT `id` FROM `done`)
AND (
    `require` IS NULL OR
    `require` IN (SELECT `id` FROM `done`)
)
ORDER BY `id`

答案 2 :(得分:1)

没有子选择的另一种解决方案

SELECT e.id FROM exercises e 
LEFT JOIN done d ON d.id = e.id 
LEFT JOIN done d_req ON d_req.id=e.require 
WHERE (d.id IS NULL AND d_req.id IS NOT NULL) 
         OR (e.require IS NULL AND d.id IS NULL)

WHERE可以简化(分配)

WHERE d.id IS NULL AND (d_req.id IS NOT NULL OR e.require IS NULL )

答案 3 :(得分:1)

这是一个工作的SQL小提琴,显示LIVE输出: http://sqlfiddle.com/#!2/0726b/29/0

也在这里粘贴查询:

SELECT id FROM 
(
  SELECT e1.* FROM exercises e1 
  LEFT JOIN done d1 ON e1.id = d1.id
  WHERE d1.id IS NULL

) AS r1

WHERE r1.`require` IS NULL OR r1.`require` IN (SELECT id from done)