TPR*_*TPR 8 sql t-sql sql-server join
假设我有两张桌子.文章和评论.
当我从articles表中选择列时,我还想在同一个select语句中选择文章的注释数...(假设这两个表之间的公共字段是articleid)
我怎么做?我可以完成它,但我不知道我的方式是否有效,所以我想学习正确的方法.
JBr*_*oks 12
这应该更有效,因为group by仅在Comment表上完成.
SELECT
a.ArticleID,
a.Article,
isnull(c.Cnt, 0) as Cnt
FROM Article a
LEFT JOIN
(SELECT c.ArticleID, count(1) Cnt
FROM Comment c
GROUP BY c.ArticleID) as c
ON c.ArticleID=a.ArticleID
ORDER BY 1
Run Code Online (Sandbox Code Playgroud)
这个应该可以。。
SELECT
article_column_1, article_column_2, count( ct.articleid) as comments
FROM
article_table at
LEFT OUTER JOIN comment_table ct ON at.articleid = ct.articleid
GROUP BY
article_column_1, article_column_2
Run Code Online (Sandbox Code Playgroud)
使用:
SELECT a.articleid,
COUNT(*) AS num_comments
FROM ARTICLES a
LEFT JOIN COMMENTS c ON c.articleid = a.articleid
GROUP BY a.articleid
Run Code Online (Sandbox Code Playgroud)
无论您要从ARTICLES表中获取什么列,都必须在GROUP BY子句中进行定义,因为它们没有对它们执行的聚合函数。