mysql 不同版本下 group by 组内排序的差异

最近发现网上找的 group by 组内排序语句在不同的mysql版本中结果不一样。
 

建表语句:

 
SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for wp_posts
-- ----------------------------
DROP TABLE IF EXISTS `wp_posts`;
CREATE TABLE `wp_posts` (
  `id` int(11) DEFAULT NULL,
  `title` varchar(6) DEFAULT NULL,
  `post_date` datetime DEFAULT NULL,
  `post_author` varchar(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 
-- ----------------------------
-- Records of wp_posts
-- ----------------------------
INSERT INTO `wp_posts` VALUES ('1', 'Title1', '2013-01-01 00:00:00', 'Jim');
INSERT INTO `wp_posts` VALUES ('2', 'Title2', '2013-02-01 00:00:00', 'Jim');
INSERT INTO `wp_posts` VALUES ('3', 'Title3', '2016-04-22 11:27:37', 'Jim');
 
 
 
 
我在网上查到group by 组内排序的基本做法是这样的:
 
方法1:
 
SELECT wp_posts.* FROM 
(
    SELECT * 
    FROM wp_posts
    ORDER BY wp_posts.post_date DESC
) AS wp_posts
 
GROUP BY wp_posts.post_author 
 
这种方法在mysql版本5.6.26是没问题的:
 
 
正确的搜出了最大的时间Title3:
 
 
 
 
在mysql版本5.7.11-log是有问题的:
 
 
搜出了最小的时间Title1:
 
 
 
这种排序方法在不同的mysql版本可能结果不一样,那有木有更好的方法呢?
我在
找到了答案。
 
 
 
方法2:
 
SELECT p1.* 
FROM wp_posts p1
INNER JOIN
(
    SELECT max(post_date) MaxPostDate, post_author
    FROM wp_posts
 
    GROUP BY post_author
) p2
  ON p1.post_author = p2.post_author
  AND p1.post_date = p2.MaxPostDate
order by p1.post_date desc
 
 
用这种方法排序,以上2种mysql版本都可以用:
 
 
版本5.6.26:
 
 
 
版本5.7.11-log:
 
 
 
 
搜索结果一样,吼吼。
 
总结一下:
 
group by 组内排序
 
方法1:
 
SELECT wp_posts.* FROM 
(
    SELECT * 
    FROM wp_posts
    ORDER BY wp_posts.post_date DESC
) AS wp_posts
 
GROUP BY wp_posts.post_author 
在不同的mysql版本中结果可能不一样;
 
方法2:
 
SELECT p1.* 
FROM wp_posts p1
INNER JOIN
(
    SELECT max(post_date) MaxPostDate, post_author
    FROM wp_posts
 
    GROUP BY post_author
) p2
  ON p1.post_author = p2.post_author
  AND p1.post_date = p2.MaxPostDate
order by p1.post_date desc

在版本5.6.26和版本5.7.11-log中结果是一样的(其他版本我没试过)。
 
 
 
posted @ 2016-04-22 14:13  zhanyd  阅读(1813)  评论(0编辑  收藏  举报