MySQL - 无法使用count(*)获得左外连接以返回count = 0的项

时间:2012-05-19 03:42:01

标签: mysql sql

我有这个架构:

mysql> describe suggested_solution_comments;
+-----------------------+----------------+------+-----+---------+----------------+
| Field                 | Type           | Null | Key | Default | Extra          |
+-----------------------+----------------+------+-----+---------+----------------+
| comment_id            | int(10)        | NO   | PRI | NULL    | auto_increment |
| problem_id            | int(10)        | NO   |     | NULL    |                |
| suggested_solution_id | int(10)        | NO   |     | NULL    |                |
| commenter_id          | int(10)        | NO   |     | NULL    |                |
| comment               | varchar(10000) | YES  |     | NULL    |                |
| solution_part         | int(3)         | NO   |     | NULL    |                |
| date                  | date           | NO   |     | NULL    |                |
| guid                  | varchar(50)    | YES  | UNI | NULL    |                |
+-----------------------+----------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> describe solution_sections;
+---------------------+---------------+------+-----+---------+----------------+
| Field               | Type          | Null | Key | Default | Extra          |
+---------------------+---------------+------+-----+---------+----------------+
| solution_section_id | int(10)       | NO   | PRI | NULL    | auto_increment |
| display_order       | int(10)       | NO   |     | NULL    |                |
| section_name        | varchar(1000) | YES  |     | NULL    |                |
+---------------------+---------------+------+-----+---------+----------------+

我的疑问是:

select   s.display_order, 
         s.section_name, 
         s.solution_section_id ,
         count(c.comment_id) AS comment_count    
FROM solution_sections s left outer join suggested_solution_comments c 
           ON (c.solution_part = s.solution_section_id) 
where      problem_id = 400    
group by   s.display_order, s.section_name, s.solution_section_id   
order by   display_order;

它只返回有计数的行> 0但如果计数为0则不返回那些行。

知道如何让它返回所有行吗? :)

谢谢!

1 个答案:

答案 0 :(得分:10)

这是因为where problem_id = 400删除了没有相应suggested_solution_comments行的行。将条件从where过滤器移动到on子句应该可以解决问题:

select s.display_order, s.section_name, s.solution_section_id ,count(c.comment_id) 
AS comment_count
from solution_sections s     
left outer join suggested_solution_comments c 
ON (c.solution_part = s.solution_section_id) AND problem_id = 400
group by s.display_order, s.section_name, s.solution_section_id   
order by display_order;