问题
Suppose I have a query like this:
SELECT
items.item_id,
items.name
GROUP_CONCAT(graphics.graphic_id) AS graphic_ids
FROM order_items items
LEFT JOIN order_graphics graphics ON graphics.item_id = items.item_id
WHERE // etc
GROUP BY items.item_id
As I understand it, the proper thing to do is to include every unaggregated column in the GROUP_BY
like so:
GROUP BY items.item_id, items.name
This is to prevent records from being lost because MySQL doesn't know how to group them. However, I'm not keen on writing a query with dozens of selected columns and having to keep all of those matched up to a GROUP BY
.
My question is, why is grouping by the primary key items.item_id
not sufficient? Sure, technically MySQL is not told explicitly what to do with ungrouped columns, but I know there will never be more records than there are primary keys, so none will get lost.
I am new to MySQL and learning as I go from, to be honest, not the cleanest legacy code, but I am trying to get the whole picture. So are there cases I am missing where records could be lost, or am I misunderstanding the reasons behind this practice?
(continued from: MySQL 'group by' with 'left join' throws away some entries)
来源:https://stackoverflow.com/questions/26386750/why-is-it-not-sufficient-to-group-by-a-primary-key