简体   繁体   English

SQL Group by Coalesce无法按预期工作

[英]SQL group by coalesce not working as expected

I have following MySQL table ( images ): 我有以下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 
...

I want to select rows where gallery_id is null or group it by gallery_id if it not null. 我想选择gallery_id为null的行,或者如果不是null则按gallery_id对其进行分组。 So expected result is: 因此,预期结果是:

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

I tried to use coalesce function to achieve this result: 我尝试使用coalesce功能来实现以下结果:

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

But it returns only rows where gallery_id is null. 但它仅返回gallery_id为null的行。 Tell me please what am I doing wrong? 告诉我我在做什么错? Thanks in advance. 提前致谢。

You could use a when in with subselect and group by 您可以使用带子选择和分组依据的when

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)
SELECT * FROM `images` where gallery_id is not null group by gallery_id 
UNION
SELECT * FROM `images` where gallery_id is null 

Your request doesn't make sense. 您的要求没有道理。 GROUP BY with SELECT * is non-sensical, because it is unclear where most of the column values come from. 带有SELECT * GROUP BY是没有意义的,因为不清楚大多数列值来自何处。

You seem to want prioritization . 您似乎想确定优先级。 . . one row for each NULL and then one for each gallery. 每个NULL一行,然后每个图库一行。

I would suggest: 我会建议:

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);

As a bonus, this is standard SQL and should work in any database. 另外,这是标准的SQL,可以在任何数据库中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM