Why is it not sufficient to group by a primary key?

风格不统一 提交于 2020-01-02 13:34:46

问题


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

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