需求说明
2张表:article,comments
文章表:article表结构:
article_id,artcile_title,content,comments
评论表:comments表结构:
comments_id,content,article_id
一篇文章对应多条评论,其中通过article_id进行对应哪些comments的记录属于哪一篇article。
现在想通过一条执行SQL,把所有article的内容和对应评论的个数读取出来,如果article无对应comments的记录说明该文章暂时无人参与评论,那么count为0.
这条SQL得怎么写?同时不至于太大性能开销。因为这里评论都放到一张表里去,可能评论数记录后续有点大。
谢谢!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
select A.article_id, A.artcile_title, A.content, B.comments_count from article A LEFT JOIN (select article_id, isnull(count(1), 0) as comments_count from comments group by article_id) B ON A.article_id = B.article_id