MySQL和MariaDB中使用GROUP BY和ORDER BY的不同ResultSet
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了MySQL和MariaDB中使用GROUP BY和ORDER BY的不同ResultSet,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1836字,纯文字阅读大概需要3分钟。
内容图文
![MySQL和MariaDB中使用GROUP BY和ORDER BY的不同ResultSet](/upload/InfoBanner/zyjiaocheng/882/4c75fd51697146ce8751f9410a5eadf1.jpg)
我有一张桌子:voj_submission具有以下结构:
CREATE TABLE IF NOT EXISTS `voj_submissions` (
`submission_id` bigint(20) NOT NULL,
`problem_id` bigint(20) NOT NULL,
`uid` bigint(20) NOT NULL,
`submission_judge_result` varchar(8) DEFAULT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8;
并且表中的数据可能像这样:
SubmissionID ProblemID UserID JudgeResult
1000 1000 User1 AC
1001 1000 User1 WA
1002 1000 User2 CE
1003 1001 User1 AC
以下SQL希望获得问题的最新判断结果:
SELECT submission_id, problem_id, submission_judge_result
FROM (
SELECT * FROM
voj_submissions
ORDER BY submission_id DESC
) s
WHERE uid = 'User1'
AND problem_id >= 1000
AND problem_id < 1010
GROUP BY problem_id
在MySQL 5.6中,它可以正常工作并返回以下结果集:
SubmissionID ProblemID JudgeResult
1001 1000 WA
1003 1001 AC
但是在MariaDB 10.0.14中,它返回:
SubmissionID ProblemID JudgeResult
1000 1000 AC
1003 1001 AC
这意味着ORDER BY DESC不在MariaDB中执行.
我怎么解决这个问题?
参考:
> https://mariadb.com/kb/en/mariadb/group-by-trick-has-been-optimized-away/
> MySQL order by before group by
解决方法:
就像@bluefeet在此post中所说的:
Using an ORDER BY in a subquery is not the best solution to this problem.
The best solution to get the max(post_date) by author is to use a subquery to return the max date and then join that to your table on both the post_author and the max date.
因此解决方案应该是:
SELECT submission_id, s1.problem_id, submission_judge_result
FROM voj_submissions s1
INNER JOIN (
SELECT MAX(submission_id) AS max_submission_id, problem_id
FROM voj_submissions
WHERE uid = 1000
AND problem_id >= 1000
AND problem_id < 1010
GROUP BY problem_id
) s2
ON s1.problem_id = s2.problem_id
AND s1.submission_id = s2.max_submission_id
这在MariaDB和MySQL中均有效.
内容总结
以上是互联网集市为您收集整理的MySQL和MariaDB中使用GROUP BY和ORDER BY的不同ResultSet全部内容,希望文章能够帮你解决MySQL和MariaDB中使用GROUP BY和ORDER BY的不同ResultSet所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。