首页 > 解决方案 > 如果结果返回 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 语句。我怎样才能做到这一点?

标签: mysqlsqlsubquerywhere-clausewindow-functions

解决方案


你可以使用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)

DB Fiddle 上的演示

凯尔的结果:

grp
G1
G2
G3

斯凯勒的结果:

grp
G1
G2

推荐阅读