SQL查询不会在连接中为每个匹配的项返回多行

时间:2011-11-05 14:42:12

标签: mysql sql database

我有两张桌子:

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    |                |
+---------------------+---------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

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    |                |
+-----------------------+----------------+------+-----+---------+----------------+

我要做的是显示solution_sections表中的section_name列表,以及每个section_name的suggested_solution_comments表中的n个匹配项。因此,对于每个部分名称,查询应该获得与之关联的suggested_solution_comments列表。

表格由suggested_solution_comments.solution_part和solution_sections.solution_section_id链接

这是我到目前为止所尝试的内容:

select section_name , comment , solution_part , display_order from solution_sections 
    left join suggested_solution_comments on 
    solution_sections.solution_section_id = suggested_solution_comments.solution_part   
    where suggested_solution_id = 188 OR suggested_solution_id IS NULL
    group by display_order;

问题是查询获取了section_name的列表,并且每个section_name获得一个匹配的注释,但不会超过一个注释。知道为什么它没有得到所有相关的评论吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

GROUP BY可能会说明您所看到的没有它的情况(根据评论更新)

select section_name , comment , solution_part , display_order 
from solution_sections 
left join suggested_solution_comments on 
solution_sections.solution_section_id = suggested_solution_comments.solution_part   
where suggested_solution_id = 188 OR suggested_solution_id IS NULL
order by display_order;

一些评论:

您的数据模型似乎有点奇怪...例如solution_partint(3)并且与solution_section_id相关联,转为autoincrement int(10)