MySQL 'group by' with 'left join' throws away some entries

泄露秘密 提交于 2019-12-24 01:59:11

问题


I have a query that looks something like this:

SELECT 
    orders.order_id,
    items.item_id, 
    GROUP_CONCAT(graphics.graphic_id) AS graphic_ids
FROM orders orders 
    LEFT JOIN order_items items ON orders.order_id = items.order_id 
    LEFT JOIN order_graphics graphics on graphics.item_id = items.item_id
WHERE // etc
GROUP BY items.item_id

Orders can have zero or more items, and items can have zero or more graphics. The goal is to get all orders matching the WHERE condition, itemize them by order item, and list the graphics on each order item, like so:

// ideal
+----------+---------+---------------+    
| order_id | item_id | graphic_ids   |
+----------+---------+---------------+
|     3097 |  NULL   | NULL          |
|     3098 |  NULL   | NULL          |
|     3099 |  NULL   | NULL          |
|     3100 |  112437 | NULL          |
|     3101 |  112677 | 127003        |
|     3102 |  112948 | 127314        |
|     3102 |  112949 | 127315        |
|     3102 |  112950 | 127316        |
|     3103 |  122807 | 138005,138006 |
+----------+---------+---------------+

However, the GROUP BY / GROUP_CONCAT clauses mean that all orders with zero items are grouped under NULL:

// reality
+----------+---------+---------------+
|     3097 |  NULL   | NULL          |
|     3100 |  112437 | NULL          |
|     3101 |  112677 | 127003        |
|     3102 |  112948 | 127314        |
|     3102 |  112949 | 127315        |
|     3102 |  112950 | 127316        |
|     3103 |  122807 | 138005,138006 |
+----------+---------+---------------+

Is there a good way to group by `item_id while still listing out all orders with no items on them?


回答1:


You should have every column that isn't an aggregate calculation in your group by clause:

SELECT 
    orders.order_id,
    items.item_id, 
    GROUP_CONCAT(graphics.graphic_id) AS graphic_ids
FROM orders orders 
    LEFT JOIN order_items items ON orders.order_id = items.order_id 
    LEFT JOIN order_graphics graphics on graphics.item_id = items.item_id
WHERE // etc
GROUP BY orders.order_id, items.item_id


来源:https://stackoverflow.com/questions/26365844/mysql-group-by-with-left-join-throws-away-some-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!