问题
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