2

我想将此问题转换为查询。估计应该是三个leftjoin和两个select

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

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

做完功法一和二,我现在可以做哪些功法?
解:3,5,7

我的逻辑流程,一步一步:(
全部)-SELECT(必需-完成)-(完成)
(1,2,3,4,5,6,7)-SELECT((1,2,3,5)- (1,2)) - (1,2)
(1,2,3,4,5,6,7) - SELECT(3,5) - (1,2)
(1,2,3,4,5 ,6,7) -(4,6) - (1,2)
(3,5,7)

如何编写查询?

4

4 回答 4

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);
于 2013-01-18T14:59:30.890 回答
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`
于 2013-01-18T15:27:24.893 回答
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 )
于 2013-01-18T18:08:21.797 回答
1

这是一个显示 LIVE 输出的有效 SQL 小提琴: 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) 
于 2013-01-18T18:18:06.987 回答