简体   繁体   中英

SQL group by coalesce not working as expected

I have following MySQL table ( 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. 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:

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

But it returns only rows where gallery_id is null. Tell me please what am I doing wrong? Thanks in advance.

You could use a when in with subselect and 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)
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.

You seem to want prioritization . . . one row for each NULL and then one for each gallery.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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