如何使用条件组创建查询

时间:2015-08-05 10:43:34

标签: mysql

我有这样的表:

+---------+---------------+
| item_id | status        |
+---------+---------------+
| 1       | active        |
| 1       | sold          |
| 1       | deleted       |
| 2       | active        |
| 2       | sold          |
| 3       | active        |
+---------+---------------+

我想要的是像这样的简单输出。但是,有一个条件。如果某个item_id已经有“已删除”状态,那么它将不再显示在此查询中。并且所有item_id都被分组为单行。

+---------+---------------+
| item_id | status        |
+---------+---------------+
| 2       | active        |
| 3       | active        |
+---------+---------------+

我尝试使用:SELECT * FROM table GROUP BY item_id,但结果并不像我预期的那样。

1 个答案:

答案 0 :(得分:1)

当一个名为status的列可能有多个值时,它没有意义。您可以使用having

执行所需操作
select item_id
from table
group by item_id
having sum(status = 'deleted') = 0;

如果您需要产品的所有状态,请将group_concat(distinct status) as statuses添加到select