2012-05-19 34 views
4

我有这个模式的项目:MySQL的 - 不能得到一个左外连接了COUNT(*)返回其中count = 0

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; 

它只返回count> 0的行,但如果count是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; 
+0

哦很不错的!解决了它谢谢你。我会在4分钟内接受SO让我这样做! – GeekedOut