If result returns null return everything

If result returns null return everything

我有以下数据集

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 一个组织和一个用户名:

select group from table where organization = 'ORG1' and username = 'SKYLER'

它将return这样:

 GROUP   
 -------
  G1   
  G2   

这就是我想要return为此查询编辑的内容,但是我有第二种情况。如果我去:

select group from table where organization = 'ORG1' and username = 'KYLE'

它 return 是空的,但我想要 return 'ORG1' 的所有组:

 GROUP  
--------
  G1 
  G2    
  G3  

所以基本上,如果我 select 一个组织内部的用户并且他们有一个分配给他们的组,我想 return 这些组。如果他们没有分配给他们的组,这意味着他们是组织的一种“超级用户”,当 Kyle 被 selected 时,它应该 return G1、G2 和 G3。我试过使用 IFNULL 函数,但 ti 不允许在其中使用 select 语句。我怎样才能做到这一点?

你的数据模型不是很清楚- organization 和 group 是什么意思。您应该考虑将数据分成 2 个表 - 一个用于关系用户名 - 组织,另一个用于组织 - 组。

虽然这对我来说没有多大意义,但您之后的查询应该是这样的:

SELECT DISTINCT `group` FROM `table` WHERE organization IN (SELECT DISTINCT organization FROM `table` WHERE organization = 'ORG1' AND username = 'KYLE') 

这应该有效:

If ((select id from table where organization = "org1" and username = "kyle" and group is null) is not null)
   then select distinct group from table where organization = "org1";
else select group from table where organization = "org1" and username = "kyle";
end if;

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

你也可以使用window函数,如果你是运行 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)

Demo on DB Fiddle

凯尔的结果:

grp
G1
G2
G3

Skyler 的结果:

grp
G1
G2