如何解决在MySQL 8中与GROUP BY一起使用时,ORDER BY不起作用
我在MySQL 8中读到了problem of wrong ordering when using "group by" has been resolved。 但是,以下查询仍然给出错误的结果。
select t.userId,ts.subjectId,case
when ts.subjectId in (15742) then 38
when ts.subjectId in (11613) then 19
END as subjectWeight
from tutor t
inner join tutor_subject ts on ts.userId = t.userId and ts.subjectId in (11613,15742)
where t.userId=207996
group by t.userId
order by subjectWeight desc;
结果:
userId subjectId subjectWeight
207996 11613 19
我目前正在按以下方式使用子查询来获取正确的结果,但是当默认值应能按预期工作时,这似乎很糟糕且不够理想。
select t.userId,case
when ts.subjectId in (15742) then 38
when ts.subjectId in (11613) then 19
END as subjectWeight
from tutor t
inner join (
select userId,subjectId
FROM tutor_subject
where subjectId in ( 11613,15742)
ORDER BY FIELD(subjectId,11613,15742) desc
limit 18446744073709551615
) ts on ts.userId = t.userId
where t.userId=207996
group by t.userId
order by subjectWeight desc;
结果:
userId subjectId subjectWeight
207996 15742 38
解决方法
我对问题有所有有益的评论(感谢@Akina),如下所示:
select t.userId,Max(case
when ts.subjectId in (15742) then 38
when ts.subjectId in (11613) then 19
END) as subjectWeight
from tutor t
inner join tutor_subject ts on ts.userId = t.userId and ts.subjectId in (11613,15742)
group by t.userId
order by subjectWeight desc;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。