coalesce的SQL组不按预期工作

时间:2016-10-15 11:58:08

标签: mysql sql

我有以下MySQL表(images):

+----+------------+-----------------------+
| id | gallery_id | path                                                                                                    |
+----+------------+-----------------------+
| 58 |       NULL | 58.jpg 
| 59 |       NULL | 59.jpg 
| 66 |          9 | 9-001.jpg 
| 67 |          9 | 9-002.jpg 
| 68 |         10 | 10-001.jpg 
| 69 |         10 | 10-002.jpg 
...

我想选择gallery_id为null的行,或者如果它不为null,则按gallery_id对其进行分组。 所以预期的结果是:

+----+------------+-----------------------+
| id | gallery_id | path                                                                                                    |
+----+------------+-----------------------+
| 58 |       NULL | 58.jpg 
| 59 |       NULL | 59.jpg 
| 66 |          9 | 9-001.jpg 
| 68 |         10 | 10-001.jpg 
...

我尝试使用coalesce函数来实现此结果:

select * from `images` group by coalesce(gallery_id, id);

但它只返回gallery_id为空的行。 请告诉我,我做错了什么?提前谢谢。

3 个答案:

答案 0 :(得分:0)

你可以使用with in in subselect和group by

select * from `images`
where (gallery_id, id ) in (select gallery_id, min(id) 
                             from `images`
                             where gallery_id is not null
                             group by gallery_id)

答案 1 :(得分:0)

SELECT * FROM `images` where gallery_id is not null group by gallery_id 
UNION
SELECT * FROM `images` where gallery_id is null 

答案 2 :(得分:0)

您的请求没有意义。 GROUP BY SELECT * NULL是非感性的,因为不清楚大多数列值的来源。

您似乎想要确定优先顺序。 。 。每个select i.* from images i where i.gallery_id is null or i.id in (select min(i2.id) from images i2 group by i2.gallery_id); 一行,然后每个库一个。

我建议:

use

作为奖励,这是标准的SQL,应该适用于任何数据库。