按优先顺序分组

时间:2016-06-06 11:19:10

标签: mysql

我有这个

+---------+--------+-------+
| article | name   |status |
+---------+--------+-------+
|    0001 | A      | enable|
|    0002 | A      | temp  |
|    0003 | B      | enable|
|    0004 | C      | enable|
+---------+--------+-------+

我想从此表'产品'中选择所有内容,但我想按名称分组,如果状态为 temp ,我想忽略启用状态,仅显示 temp 状态

的产品

查询后的结果将是:

+---------+--------+-------+
| article | name   |status |
+---------+--------+-------+
|    0002 | A      | temp  |
|    0003 | B      | enable|
|    0004 | C      | enable|
+---------+--------+-------+

你能帮我构建一下这个查询吗?

2 个答案:

答案 0 :(得分:3)

如果在组中找到至少一个temp,请显示它。否则显示启用

select article, name, if(sum(status='temp'), 'temp', 'enable') 
    from  thetable
  group by name

要获取与临时状态对应的文章,请使用此类查询

select * from table1 
   where status = 'temp' 
union 
select * from table1 
   where name not in (select distinct name from table1 where status = 'temp' )

答案 1 :(得分:1)

试试这个,希望对你有帮助;)

SQL Fiddle

MySQL 5.6架构

CREATE TABLE table1
    (`article` int, `name` varchar(1), `status` varchar(6))
;

INSERT INTO table1
    (`article`, `name`, `status`)
VALUES
    (0001, 'A', 'enable'),
    (0002, 'A', 'temp'),
    (0003, 'B', 'enable'),
    (0004, 'C', 'enable')
;

查询1

select  t1.*
from table1 t1
inner join (
  select count(distinct status) cnt, name, group_concat(status) as names from table1 group by name
) t2 on t1.name = t2.name
and (t2.cnt = 1 or (find_in_set('temp', names) > 0 and t1.status = 'temp'))
group by t1.name, t1.status

<强> Results

| article | name | status |
|---------|------|--------|
|       2 |    A |   temp |
|       3 |    B | enable |
|       4 |    C | enable |