Mysql Group By implementation details - which row mysql chooses in a Group By query without operators?

穿精又带淫゛_ 提交于 2020-01-06 15:22:16

问题


I have a table with multiple rows per "website_id"

CREATE TABLE `MyTable` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `tagCheckResult` int(11) DEFAULT NULL,
  `website_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `IX_website_id` (`website_id`),
) ENGINE=InnoDB;

I am trying to select the latest entry per website_id

-- This creates a temporary table with the last entry per website_id, and joins it
-- to get the entire row
SELECT *
FROM `WebsiteStatus` ws1 
JOIN (
    SELECT MAX(id) max_id, website_id FROM `WebsiteStatus` 
    GROUP BY website_id) ws2
ON ws1.id = ws2.max_id

Now, I know the correct way to get the last row per website_id is as above. My qusetion is - I also tried the following simpler query, at it seemed to return the exact same results as above:

SELECT * FROM `WebsiteStatus` 
GROUP BY website_id
ORDER BY website_id DESC

I know that in principle GROUP BY without operators (e.g. MAX), like I do in my 2nd query can return any of the relevant rows ... but in practice it returns the last one. Is there an implementation detail in mysql that guarantees this is always the case?

(Just asking for academic curiosity, I know the 1st query is "more correct").

来源:https://stackoverflow.com/questions/13700456/mysql-group-by-implementation-details-which-row-mysql-chooses-in-a-group-by-qu

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