MySQL查询需求:优先展示关注用户消息并按日期降序排序
问题描述
现有两张数据表:
- messages表(结构及数据):
postId | createDateTime | userId | message 3 | 2011-04-11 07:08:46 | 3 | A 4 | 2011-04-11 08:08:46 | 1 | B 5 | 2011-04-13 09:08:46 | 3 | C 6 | 2011-04-14 09:08:46 | 2 | D 7 | 2011-04-14 10:08:46 | 1 | D
- followers表(记录用户关注关系,结构及数据):
ID | userId |following| 1 | 60 | 1 | 2 | 60 | 2 | 3 | 48 | 1 |
需求:查询用户ID为60时,优先展示其关注用户(ID1、2)的消息,所有消息按日期降序排序,非关注用户的消息排在末尾,期望结果如下:
postId | createDateTime | userId | message 7 | 2011-04-14 10:08:46 | 1 | D 6 | 2011-04-14 09:08:46 | 2 | D 4 | 2011-04-11 08:08:46 | 1 | B 5 | 2011-04-13 09:08:46 | 3 | C 3 | 2011-04-11 07:08:46 | 3 | A
原查询语句存在日期排序异常,语句如下:
SELECT m.postId,m.updateDateTime,m.userId, m.message, f.followerId, f.userId FROM messages m left join followers f on m.userId = f.followerId and f.userId=60 order by f.followerId desc, m.updateDateTime desc;
修正后的查询语句
SELECT m.postId, m.createDateTime, m.userId, m.message FROM messages m LEFT JOIN followers f ON m.userId = f.following AND f.userId = 60 ORDER BY CASE WHEN f.following IS NOT NULL THEN 0 ELSE 1 END, m.createDateTime DESC;
问题解析
原语句的核心问题:
- 字段名错误:原查询使用了
updateDateTime,但数据表中实际字段为createDateTime,导致排序依据的字段不存在,引发排序异常。 - 排序逻辑错误:用
f.followerId desc作为首要排序条件,会让关注用户的消息按userId倒序排列,无法实现“所有关注用户消息优先、再统一按日期降序”的需求。
修正说明:
- 替换错误字段
updateDateTime为数据表实际存在的createDateTime。 - 用
CASE表达式生成优先级标记:关注用户的消息标记为0,非关注用户的标记为1,确保关注用户的消息整体排在前面。 - 后续统一按
createDateTime降序排序,完全匹配需求中的排序规则。
内容的提问来源于stack exchange,提问作者Mubasher
相关产品推荐
相关产品推荐

