sql - 如果一个或多个用户发表了评论,请选择用户组
问题描述
考虑以下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:至少有 1 位用户发表评论的组
- 查询 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 = ''
)评论,但我不知道如何在我的查询中解决这个问题。
任何帮助将不胜感激。
解决方案
您可以使用exists
和not 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
。
推荐阅读
- java - 统计所有在 Hashmap 中添加键值的调用
- nuxt.js - 使用 purgecss 的 `rejected` 选项时,Tailwind 不提供拒绝/清除的样式列表
- python - Selenium 有没有办法阻止 ctrl+c 关闭浏览器窗口
- javascript - Laravel Mix 不加载资源
- excel - 如何自动格式化不包含换行符或缩进的代码?
- python - macOS:如何更改 PATH 环境变量?
- javascript - 文本格式化 CrystalReports 的问题
- python - 使用 python 拆分或分隔这个列表,只要有一个空列表`[]`
- sql - 创建类别 SQL
- python - 从 JAX 中的多元正态分布采样会产生类型错误