簡體   English   中英

MySQL - 無法使用count(*)獲得左外連接以返回count = 0的項

[英]MySQL - can't get a left outer join with a count(*) to return the items where 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;

它只返回計數> 0的行,但如果計數為0則不返回這些行。

知道怎么讓它返回所有行嗎? :)

謝謝!!

這是因為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM