首页 > 解决方案 > 查找所有共享特定评论的记录

问题描述

我有一个现有的table1

User   Comment  Group
---------------------
1      foo      a
2      bar      a
3      baz      b
4      123      a
5      bar      c
6      foo      d
7      654      a

假设我需要选择所有UsersComment foo

select * from [table1] t1 where t1.[Comment] = 'foo';

User   Comment   Group
---------------------
1      foo       a
6      foo       d

现在我想找到同一个Groups中的所有用户:

User   Comment  Group
---------------------
1      foo      a
2      bar      a
4      123      a
6      foo      d

我怎样才能做到这一点?我是这样想的:

select t1.*
from   [table1] t1
left join [table1] t2 on t1.[User] = t2.[User]
and t1.[Comment] = 'foo'

但这是返回所有记录[table1]。我究竟做错了什么?

标签: sqlsql-serverdatabasetsqlsubquery

解决方案


你可以使用exists

select t.*
from mytable t
where exists (
    select 1 from mytable t1 where t1.comment = 'foo' and t1.group = t.group
)

对于此查询的性能,您需要在(comment, group).


推荐阅读