Sql 选择一条记录中条件为真的记录

Sql 选择一条记录中条件为真的记录,sql,sql-server,Sql,Sql Server,我需要从下表中的行中选择cid、project和owner,其中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

我需要从下表中的行中选择cid、project和owner,其中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 

如果真实数据中有大量记录,中的
可能会对性能造成相当大的影响。并不是说不应该使用它,而是应该小心使用。对于带有相关项的IN子句,您可能会有一些性能问题。但是对于内部联接版本。。您可以使用适当的索引来保持高性能。。。如果出于这个原因,这两个版本是公开的..谢谢大家的输入。当我用cid和project替换id时,scaisEdge您的内部联接工作正常。@fallingdog应答已更新为正确的列。好吧,如果我的答案是正确的,或者引导您找到正确的解决方案,请将其标记为已接受……看看这里的@scaisEdge-酷,我不知道。我猜你每天都会学到新东西。虽然我会使用常规的
连接而不是外部连接,但你的查询很好。谢谢你的反馈。我刚刚恢复了精神。我现在明白了,内部连接(join)更切题。中间选择不是多余的吗?你就不能直接把第一个加入最后一个吗?是的,我想你是对的。就像下面的斯凯里奇的加入。我在想,“如果我不尝试和所有的专栏一起工作,也许它会优化一些东西…”但也许我只是让它变得更难,然后它需要。