首页 > 解决方案 > 如果一个或多个用户发表了评论,请选择用户组

问题描述

考虑以下table1

user   group   comment
----------------------
 1     a       foo
 2     a
 3     a
 4     b       bar
 5     c
 6     c
 7     d
 8     d
 9     d
10     d
11     e       bax
12     e       baz

我需要进行 2 个查询,每个查询都返回组:

查询1的结果:

user   group   comment
----------------------
 1     a       foo
 2     a
 3     a
 4     b       bar
11     e       bax
12     e       baz

查询2的结果:

user   group   comment
----------------------
 5     c
 6     c
 7     d
 8     d
 9     d

user我尝试了以下方法,但随后我在两组中看到了一些相同的 s:

select  * 
from    [table1] t1
where   t1.[group] in (
    select distinct [group] from [table] where [comment] <> ''
)
order by t1.[user] asc

select  * 
from    [table1] t1
where   t1.[group] in (
    select distinct [group] from [table] where [comment] = ''
)
order by t1.[user] asc

然后我意识到这是因为在同一个组中,可以设置(comment <> '')和不设置(comment = '')评论,但我不知道如何在我的查询中解决这个问题。

任何帮助将不胜感激。

标签: sqlsql-servertsql

解决方案


您可以使用existsnot exists

这为您提供了已发布评论的组的用户。

select t.*
from mytable t
where exists (
    select 1 from mytable t1 where t1.group = t.group and t1.comment is not null
)

要获取组的用户而无需任何评论,您只需exists转向not exists


推荐阅读