2015-07-28 63 views
1

水平JOIN我想查詢2個表,一個學生和包含與學生的意見另一個表。與MySQL

學生表:

| ID | Name | 
------------- 
| 1 | John | 
| 2 | Alex | 

評語表:

| ID | Student ID | Comment | 
----------------------------- 
| 1 | 1   | phoned | 
| 2 | 1   | emailed | 
| 3 | 2   | phoned | 
| 4 | 2   | emailed | 
| 5 | 2   | mailed | 

我所需的輸出會是這樣的:

| Student | Comment 3 | Comment 2 | Comment 1 | 
----------------------------------------------- 
| John | null  | phoned | emailed | 
| Alex | mailed | emailed | called | 

任何幫助,將不勝感激。這樣做將是如下的

+1

有多少種不同類型的評論是可能的嗎? –

+0

我想通過ID DESC例如 – user3253002

+0

設置的5個限度,秩序和意見是純文本,這樣可以一切 – user3253002

回答

0

方式一:

SELECT students.name, c1.comment, c2.comment, c3.comment FROM students 
LEFT JOIN (SELECT * FROM comments WHERE comment = 'phoned') as c1 
ON c1.student_id = students.id 
LEFT JOIN (SELECT * FROM comments WHERE comment = 'emailed') as c2 
ON c2.student_id = students.id 
LEFT JOIN (SELECT * FROM comments WHERE comment = 'mailed') as c3 
ON c3.student_id = students.id 

你必須增加的連接數爲每個評論的類型。

+0

感謝您的答案,但我不知道評論的價值是先驗的,這可以做任何事情...... – user3253002

+0

然後你不應該遵循這種方法。正如你所提到的那樣,獲得輸出將非常困難。您最好使用簡單的組,然後更改PHP中的表示或您可能使用的任何其他服務器代碼。 – Vishal

+0

我必須創建一個視圖.. – user3253002