2015-06-29 70 views
0

我有兩張表 - 學生和科目。學生表存儲所有學生名單和學科表格存儲這些學生已經註冊的所有科目。MYSQL中的一對多關係產生錯誤結果

CREATE TABLE students 
    (`id` int, `name` varchar(7)); 

INSERT INTO students 
    (`id`, `name`) 
VALUES 
    (1, 'Jason'), 
    (2, 'Matt'), 
    (3, 'Abram') 
    ; 

CREATE TABLE subjects 
    (`id` int,`student_id` int, `subject` varchar(15)); 

INSERT INTO subjects 
    (`id`,`student_id`, `subject`) 
VALUES 
    (1,1, 'Math'), 
    (2,1, 'Physics'), 
    (3,2, 'Chemistry'), 
    (4,2, 'Math'), 
    (5,2, 'English'), 
    (6,3, 'Chemistry') 
    ; 

而且在執行下面的查詢

SELECT STUD.id,STUD.name,SUB.subject 
FROM students AS STUD 
LEFT JOIN subjects AS SUB 
ON STUD.id=SUB.student_id 
; 

給設置這樣的結果(這是不是我試圖讓)

++++++++++++++++++++++++++++++++++++ 
id  | name | subject   | 
++++++++++++++++++++++++++++++++++++ 
| 1 | Jason | Math    | 
------------------------------------ 
| 1 | Jason | Physics   | 
------------------------------------ 
| 2 | Matt | Chemistry   | 
------------------------------------ 
| 2 | Matt | Math    | 
------------------------------------ 
| 2 | Matt | English   | 
------------------------------------ 
| 3 | Abram | Chemistry   | 
------------------------------------ 

學生在被反覆名單。

,當我嘗試

SELECT STUD.id,STUD.name,SUB.subject 
FROM students AS STUD 
LEFT JOIN subjects AS SUB 
ON STUD.id=SUB.student_id 
GROUP BY STUD.id 
; 

我得到的(這又是錯的)

++++++++++++++++++++++++++++++++++++ 
id  | name | subject   | 
++++++++++++++++++++++++++++++++++++ 
| 1 | Jason | Math    | 
------------------------------------ 
| 2 | Matt | Chemistry   | 
------------------------------------ 
| 3 | Abram | Chemistry   | 
------------------------------------ 

我想要的結果看起來是這樣的:

++++++++++++++++++++++++++++++++++++++++++++++++ 
id  | name | subject      | 
++++++++++++++++++++++++++++++++++++++++++++++++ 
| 1 | Jason | Math, Physics     | 
------------------------------------------------ 
| 2 | Matt | Chemistry,Math ,English  | 
------------------------------------------------ 
| 3 | Abram | Chemistry      | 
------------------------------------------------ 

我在關係新手數據庫。 爲什麼羣體沒有給出正確的結果? 在此先感謝。

SQL FIDDLE

回答

1

您可以通過

SELECT STUD.id,STUD.name,GROUP_CONCAT(SUB.subject) as subject 
FROM students AS STUD 
LEFT JOIN subjects AS SUB 
ON STUD.id=SUB.student_id 
GROUP BY STUD.id; 

實現這個其實它給出正確的結果,當你在SQL中有組通過一些列它將只返回組第一記錄,以便爲您期望的結果,你需要使用GROUP_CONCAT函數,它返回給定列中的所有逗號分隔值。

+0

謝謝隊友。有效。 –