【问题标题】:If result returns null return everything如果结果返回 null 则返回所有内容
【发布时间】:2020-09-08 19:12:55
【问题描述】:

我有以下数据集

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  

因此,基本上,如果我在组织内部选择了一个用户并且他们分配了一个组,我想返回这些组。如果他们没有分配给他们的组,这意味着它们是组织的一种“超级用户”,如果选择凯尔,它应该返回G1,G2和G3。我尝试过使用 IFNULL 函数,但它不允许在其中使用 select 语句。我怎样才能做到这一点?

【问题讨论】:

    标签: mysql sql subquery where-clause window-functions


    【解决方案1】:

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

    Demo on DB Fiddle

    凯尔的结果:

    grp
    G1
    G2
    G3
    

    Skyler 的结果:

    grp
    G1
    G2
    

    【讨论】:

    • 感谢您的回复。我已经尝试过这些解决方案,当它是一个与他们关联的组的用户时,它会正确返回行组。如果用户没有与之关联的组,则返回 null 而不是所有组
    • @user2924127:我的错。我修复了查询(并测试了它们)。这似乎可以满足您现在的要求。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      这应该可行:

      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;
      

      【讨论】:

        猜你喜欢
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-12
        • 2020-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-12
        相关资源
        最近更新 更多