# group by后排序问题

0

1.针对一个文章，我有N多的评论
2.现在我想获取到每篇文章最新的评论

SELECT FROM (SELECT FROM old_chapter_check_list ORDER BY id DESC) AS t GROUP BY cid LIMIT 10

## 5个回答

1

1、一定不要子查询的，确认评论中不包含某种分隔符的话(比如“|||”)使用substring_index(group_concat))函数处理：

``````select substring_index(group_concat(comment_content order by id desc separator '|||'),'|||',1) cmt,cid from old_chapter_check_list group by cid limit 10;
``````

2、不确定是否包含特殊字符的写法，先取出有最新评论的10个文章最新id值(唯一自增主键的话)再进行联表查询

``select a.cid,a.comment_content from old_chapter_check_list a join (select max(id) maxid from old_chapter_check_list group by cid order by maxid desc limit 10) b on a.id=b.maxid;``
1
``````SELECT * FROM old_chapter_check_list GROUP BY cid ORDER BY id DESC LIMIT 10

SELECT max(id) FROM old_chapter_check_list GROUP BY articleid

select * from old_chapter_check_list where cid = maxid
``````
0

0

``````1、select * from tb A where id in (select id from tb B where A.class = B.class order by age desc limit 2)

2、select * from tb B where 2 > (select count(*) from tb B where A.class = B.class and B.age > A.age)

3、select A.id,A.name,A.age,A.class from group_by_test A left join group_by_test B on A.class = B.class and A.age < B.age group by A.name,A.age,A.class having count(B.age)<2``````
0

SELECT *,MAX(id) max_id FROM old_chapter_check_list GROUP BY cid order by max_id LIMIT 10