![](/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.