2011-11-05 18 views
0

每個匹配項返回多個行我有2個表:SQL查詢不會在加入

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的名單,和n匹配來自suggested_solution_comments表中每個section_name的項目。因此,對於每個部分名稱,查詢都應該獲得與其關聯的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匹配評論,但不多於一條評論。任何想法爲什麼它沒有得到所有相關的評論?

謝謝!

回答

2

GROUP BY可以解釋你所看到的嘗試沒有它(UPDATE按照評論)

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)

+0

它的工作得到多個評論,但由於某種原因,它是在某種程度上隨機順序中的項目:)有沒有辦法讓項目顯示根據表中的section_name的順序? – GeekedOut

+0

@GeekedOut嘗試使用上面的更新...如果這不起作用:「表中的section_name的順序」是什麼意思?按字母順序? – Yahia

+0

我的意思是更多,因爲它們在數據庫中列出。我猜他們的ID,這是我甚至沒有打擾在select子句中列出的record_id。我會在這裏嘗試一下,讓你知道它是怎麼回事:)順便說一句,當你在order by子句中列出4列時,它有什麼作用?這實現了什麼? – GeekedOut