mysql从结果中group_MySQL查询在GROUP BY中排序结果

bd96500e110b49cbb3cd949968f18be7.png

I'm coding a forum system and I'm trying to get the last post in a topic. The problem is I'm grouping the results on the topic id and I can't figure out a way to get the last reply to be displayed in the grouped data.

Here is my query so far:

SELECT SQL_CACHE users.user_id,

users.username,

topics.title,

topics.topic_id,

topics.previews,

topics.date_added,

posts.post_id,

last.username AS last_username,

last.user_id AS last_user_id,

MAX( posts.post_id ) AS last_post_id,

posts.date_added AS last_data

FROM `topics`

LEFT JOIN `users` ON users.user_id = topics.user_id

LEFT JOIN `posts` ON ( posts.topic_id = topics.topic_id )

LEFT JOIN `users` AS last ON ( last.user_id = posts.user_id )

WHERE fcat_id = '2'

GROUP BY topics.topic_id

解决方案

You can do something like

SELECT *, `last`.`user_id` AS last_user_id FROM

(

SELECT users.user_id,

users.username,

topics.title,

topics.topic_id,

topics.previews,

topics.date_added,

posts.post_id,

MAX( posts.post_id ) AS last_post_id,

posts.date_added AS last_data

FROM `topics`

LEFT JOIN `users` ON users.user_id = topics.user_id

LEFT JOIN `posts` ON ( posts.topic_id = topics.topic_id )

WHERE fcat_id = '2'

GROUP BY topics.topic_id

) AS `tst`

LEFT JOIN `posts` ON ( posts.post_id = tst.last_post_id )

LEFT JOIN `users` AS `last` ON ( `last`.user_id = posts.post_id )

Just set your selects properly and maybe alias the posts JOIN which is outside the subquery

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值