2

我正在尝试创建一个连接两个表并返回计数的 SQL 语句。即使没有找到计数的项目,我也需要返回所有记录。

如果我这样做:

SELECT s.subject,s2.subject from subjects s 
left join subjects s2 on s.parent_id = s2.id

这很好,但没有计数。我尝试通过这样做将它加入到我需要依靠的另一个表中:

SELECT s.subject,s2.subject,count(q.id) from subjects s 
left join subjects s2 on s.parent_id = s2.id 
join questions q on q.subject_id = s.id

但我只得到一个根本没有任何意义的结果。

4

2 回答 2

1

如果您可以有零COUNT个问题,则需要LEFT JOIN

SELECT s.subject, s2.subject, NVL(q.q_count,0) as question_count 
FROM subjects s 
LEFT JOIN subjects s2 ON s.parent_id = s2.id 
LEFT JOIN (SELECT q.subject_id, count(1) as q_count 
  FROM questions q
  GROUP BY q.subject_id) q ON q.subject_id = s.id
于 2012-04-08T13:13:15.347 回答
1

试试这个:

 SELECT s.subject, s2.subject, COUNT(q.id) 
 FROM subjects s 
 LEFT JOIN subjects s2 ON s.parent_id  = s2.id 
 LEFT JOIN questions q ON q.subject_id = s.id 
 GROUP BY s.subject_id, s2.subject_id, q.subject_id
于 2012-04-08T13:19:23.890 回答