我想在一个查询中结合2个SQL查询 - 使用计数

时间:2015-12-04 14:52:09

标签: mysql sql sql-server

我有两张桌子:

表1:Questions

-Id
-Name
-AdditionalInformation
-Author
-QuestionCategory
-Date
-Time

表2:Comments

- Id
- QuestionId

我需要得到Question的所有表格以及每个QuestionID的评论数量。

有人可以帮忙吗?

我尝试了什么:

select * from Questions
union
SELECT Count(ID) FROM Comments Group By QuestionId

2 个答案:

答案 0 :(得分:2)

select q.*, c.commentCount
from questions q left join
     (select questionid, count(id) as commentCount
      from comments
      group by questionid
     ) c
     on c.questionid = q.id

答案 1 :(得分:0)

以上答案略有增强版本.. 如果问题没有任何评论,它将显示0而不是NULL。

select q.*, COALESCE(c.commentCount,0)
from questions q left join
     (select questionid, count(id) as commentCount
      from comments
      group by questionid
     ) c
     on c.questionid = q.id