场景是这样的 有一个文章表 article字段:aid content 还有一个点赞表 praise 字段: id aid time 点赞表的aid字段存的是对应文章的aid 现在要获取文章列表但是要根据点赞数从大到小排列,这个SQL怎么写? 谢谢。
数据量大的话,left join相对比较慢,如果是分页显示或者只是求前面几十条的数据,可以先求点赞表排序好了的aid,再在文章表中找这些aid对应的文章
select a.content from article a left join praise b on a.aid=b.aid order by b.time desc
SELECT a.aid, a.content, pr.praiseCount FROM article a LEFT JOIN (SELECT p.aid, count(1) AS praiseCount FROM praise p GROUP BY p.aid) pr ON a.aid = pr.aid ORDER BY pr.praiseCount DESC
select a.aid,count(p.aid) num from article a left join praise p on a.aid=p.aid group by p.aid order by num desc;
数据量大的话,left join相对比较慢,如果是分页显示或者只是求前面几十条的数据,可以先求点赞表排序好了的aid,再在文章表中找这些aid对应的文章
select a.content from article a left join praise b on a.aid=b.aid order by b.time desc
select a.aid,count(p.aid) num from article a left join praise p on a.aid=p.aid group by p.aid order by num desc;