4

我有这个架构:

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,则不返回这些行。

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

谢谢!!

4

1 回答 1

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;
于 2012-05-19T03:47:31.697 回答