有数据表 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)
