Mysql多个连接和计数

时间:2012-04-08 13:08:09

标签: mysql join

我正在尝试创建一个连接两个表并返回计数的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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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