您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

mysql group by 组内排序

2024/5/1 14:06:45发布31次查看
有数据表 comments ------------------------------------------------ | id | newsid | comment | thetime | ------------------------------------------------ | 1 | 1 | aaa | 11 | ------------------------------------------------ | 2 | 1 | bbb | 1
有数据表 comments
------------------------------------------------
| id | newsid | comment | thetime |
------------------------------------------------
| 1  |        1      |         aaa    |     11       |
------------------------------------------------
| 2  |        1      |         bbb    |     12       |
------------------------------------------------
| 3  |        2      |         ccc     |     12       |
------------------------------------------------
newsid是新闻id,每条新闻有多条评论comment,thetime是发表评论的时间
现在想要查看每条新闻的最新一条评论:
select * from comments group by newsid 显然不行
select * from comments group by newsid order by thetime desc是组外排序,也不行
下面有两种方法可以实现:
(1)
selet tt.id,tt.newsid,tt.comment,tt.thetime from(  
select id,newsid,comment,thetime from comments order by thetime desc) as tt group by newsid
(2)
select id,newsid,comment,thetime from comments as tt group by id,newsid,comment,thetime having
 thetime=(select max(thetime) from comments where newsid=tt.newsid)
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product