【问题标题】:Selecting a group with the same value but with one exception选择具有相同值但有一个例外的组
【发布时间】:2009-05-20 02:05:42
【问题描述】:

我有一个带有外键、状态、代码的表

我想选择具有相同外键的组 一条记录的代码为 001,状态为“不完整” 其余的都必须具有“已完成”的状态

id   foreignkey                    code                 status
---------------------------------------------------------------------
01 ---  04   -------------         009   ---------    completed 
02 ---  04   -------------         009   ---------    completed 
03 ---  04   -------------         009   ---------    completed 
04 ---  04   -------------         009   ---------    completed 
05 ---  04   -------------         009   ---------    completed 
06 ---  04   -------------         009   ---------    completed 
07 ---  04   -------------         009   ---------    completed 
08 ---  04   -------------         001   ---------    incomplete

假设外键“04”有 8 条记录,其中 5 条状态为完成,2 条状态为“未知”,1 条状态为“未完成”。那么查询不应该返回这个组。

仅当一种状态为“未完成”且代码为 001 且所有其余状态为“已完成”状态时

我将在 mysql 中运行它,谢谢,感谢您的帮助。

【问题讨论】:

    标签: sql mysql


    【解决方案1】:

    我不熟悉 MySQL,但这应该是相当通用的语法 -

    select * from table
      where status in ('completed','incomplete') 
       and foreignkey in (
                         select foreignkey 
                         from table 
                         where code='001' 
                          and staus='incomplete' 
                         group by foreignkey 
                         having count(*) =1)
    

    【讨论】:

    • 如问题所指,这将如何“不返回”有 2 个未知数的组?
    • 是的,我一开始忘记了这一点 - 添加了 staus in 子句以适应。
    • +1 非常干净的解决方案,我建议你把它分成几行,这样它更具可读性。
    • 虽然查询返回“已完成”状态的记录加上 1 条“未完成”的记录,但当我直接查询该外键时(从表中选择 *foreignkey = )我看到它有记录“未知”(或其他状态)
    【解决方案2】:
    select t.foreignkey
    from t
    where t.code = '001' and not exists (
      select 1
      from t t2
      where t2.foreignkey = t.foreignkey and t2.id <> t.id and t2.code <> '009')
    

    然后您可以将其加入 t 以获取每个组的实际数据。如果一个组中可能有多个不完整的项目,则需要“选择不同的外键”。

    【讨论】:

      【解决方案3】:

      您可以使用 GROUP BY 来完成此操作:

      select foreignkey
      from yourtable
      group by foreignkey
      having sum(case when code='001' and status='incomplete' then 1 else 0 end) = 1
      and sum(case when status='completed' then 1 else 0 end) = count(*) - 1
      

      HAVING 子句指定每个外键组的条件。第一个条件表示必须有一行代码为 001 且状态为 Incomplete。第二个条件是必须完成所有其他行。

      【讨论】:

        猜你喜欢
        • 2021-10-21
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        • 2022-08-17
        • 2019-05-31
        • 1970-01-01
        • 1970-01-01
        • 2015-07-17
        相关资源
        最近更新 更多