![](/img/trans.png)
[英]Select records where every record in one-to-many join matches a condition
[英]select records where condition is true in one record
我需要从下表的行中选择cid,项目和所有者,其中cid /项目组合的一或多个行的所有者为1。
cid | project | phase | task | owner
-----------------------------------
1 | 1 | 1 | 1 | 1
1 | 1 | 1 | 2 | 2
1 | 1 | 1 | 3 | 2
2 | 1 | 1 | 1 | 1
2 | 1 | 1 | 2 | 1
3 | 1 | 1 | 3 | 2
我的输出表应如下所示:
cid | project | phase | task | owner
-----------------------------------
1 | 1 | 1 | 1 | 1
1 | 1 | 1 | 2 | 2
1 | 1 | 1 | 3 | 2
2 | 1 | 1 | 1 | 1
2 | 1 | 1 | 2 | 1
下面的查询是我想出的。 看来确实可以,但是我的信心很低。 查询是解决问题的有效方法吗?
select task1.cid, task1.project, task1.owner
from
(select cid, project, owner from table) task1
right join
(select distinct cid, project, owner from table where owner = 1) task2
on task1.cid = task2.cid and task1.project = task2.project
(我没有从示例输出中删除阶段和任务列,以便于比较。)
您可以简单地使用IN子句
select cid, project, owner
from table
where cid in (select distinct id from table where owner = 1)
或带有子查询的内部联接
select a.cid, a.project, a.owner
from table a
INNER JOIN ( select distinct cid , project
from table where owner = 1
) t on t.cid = a.cid and t.project = a.project
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.