mysql - 如果结果返回 null 则返回所有内容
问题描述
我有以下数据集
ID | GROUP | ORGANIZATION | USERNAME
----------------------------------------------------
1 G1 ORG1 SKYLER
2 G1 ORG1 BRAD
3 G1 ORG1 CHAD
4 G2 ORG1 SKYLER
5 G3 ORG1 THAMIUS
6 (null) ORG1 KYLE
7 G7 ORG2 TAYLOR
8 G7 ORG2 CLAY
9 G7 ORG2 WILL
10 G8 ORG2 KYLE
然后我有一个选择组织和用户名的查询:
select group from table where organization = 'ORG1' and username = 'SKYLER'
它会返回这个:
GROUP
-------
G1
G2
这是我想要为这个查询返回的,但是我有第二种情况。如果我走:
select group from table where organization = 'ORG1' and username = 'KYLE'
它返回null,但我想要的是返回'ORG1'的所有组:
GROUP
--------
G1
G2
G3
所以基本上,如果我在组织内选择一个用户并且他们有一个分配给他们的组,我想返回这些组。If they have no groups assigned to them, that means they are a kind of "super user" for the organization and it should return G1, G2, and G3 when Kyle is selected. 我尝试过使用 IFNULL 函数,但它不允许在其中使用 select 语句。我怎样才能做到这一点?
解决方案
你可以使用exists
:
select distinct grp
from mytable
where organization = 'ORG1' and grp is not null and (
username = 'SKYLER'
or exists (
select 1
from mytable
where organization = 'ORG1' and username = 'SKYLER' and grp is null
)
)
如果您正在运行 MySQL 8.0,您还可以使用窗口函数:
select distinct grp
from (
select t.*, max(username = 'KYLE' and grp is null) over() is_admin
from mytable t
where organization = 'ORG1'
) t
where grp is not null and (username = 'KYLE' or is_admin = 1)
凯尔的结果:
grp
G1
G2
G3
斯凯勒的结果:
grp
G1
G2
推荐阅读
- c# - 关于 StyleCop 的一些问题
- mysql - 是否可以使用 JOOQ 数据绑定实现 MySQL JSON_MERGE_PATCH?
- visual-studio-code - 为什么vscode侧边栏显示蓝屏?
- applescript - 我可以定义一个可以与我的脚本一起使用的全局处理程序吗?
- python - Python-SQL - 改进数据框
- python - 为什么每次尝试替换文件中的文本时程序都会崩溃?
- angular - 对 observable subscribe 参数进行类型检查
- c++ - 类中的同步变量,它们是父类和子类
- splunk - 使用 splunk 进行 API 监控
- typescript - 当我尝试用黄瓜运行量角器测试时,出现以下错误消息“E/launcher - Process exited with error code 1”