选择具有相同值但有一个例外的组

时间:2009-05-20 02:05:42

标签: sql mysql

我有一个包含外键,状态,代码的表

我想选择具有相同外键的组 一条记录的代码为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中运行它,谢谢,感谢帮助。

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

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以获取每个组的实际数据。如果组中可能有多个不完整的项目,则需要“选择不同的外键”。

答案 2 :(得分:0)

您可以使用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。第二个条件是必须完成所有其他行。