我有这张桌子
问题
ID | Name
1 question1
2 question1
3 question1
ANSWER
ID | question_id
1 1
2 1
3 2
COMMENT
ID | question_id | answer_id
1 NULL 1
2 1 NULL
3 2 NULL
一个问题可以有多个答案和评论,
答案属于1个问题,
并且注释属于1个单一答案或问题(如在Stackoverflow中自动选择)。
我想订购有关最高金额答案和评论的问题。
我仍然是sql语句的新手,做了一些不再有意义的查询!我想发布它们,但我认为它有点不相关,因为它们可能是错的!如果你想让我发布它们,我会展示一些工作'。
由于
答案 0 :(得分:1)
如果我理解正确,你只需要加入和聚合:
select q.*, a.numanswers, c.numcomments
from questions q left join
(select question_id, count(*) as numanswers
from answers a
group by question_id
) a
on q.id = a.question_id left join
(select question_id, count(*) as numcomments
from comments c
where question_id is not null
group by question_id
) c
on q.id = c.question_id
order by (numanswers + numcoments) desc
这会得到关于问题的评论数量(而不是关联的答案),但这似乎是你要求的。