2015-07-10 45 views
0

我有這個表:Mysql的自聯接給人怪異的結果

id|subject   | parent_id 
1 |ladbore   | 2 
2 |quod    | NULL 
3 |cumque   | 6 
4 |ut    | 3 
5 |sed    | NULL 
6 |reprehenderit | 1 
7 |qui    | 4 
8 |eum    | 6 
9 |deserunt   | 6 
10 |et    | 6 

現在我已經創建了一個自連接來獲取所有科目包括父的,像這樣的個體的名稱:

SELECT 
`subject`. `id`, 
`subject`.`subject` AS `subject_name`, 
`parent`.`subject` AS `parent_name` 
FROM 
`subjects` AS `subject` 
LEFT JOIN 
`subjects` AS `parent` 
ON 
`parent`.`id` = `subject`.`id`; 

但是這給了我下面的怪異的結果:

id subject_name parent_name 
1 labore   labore 
2 quod   quod 
3 cumque   cumque 
4 ut    ut 
5 sed    sed 
6 reprehenderit reprehenderit 
7 qui    qui 
8 eum    eum 
9 eserunt   deserunt 
10 et    et 

爲什麼這給出錯誤的結果?

回答

1

由於您擁有parent.id = subject.id,因此您只需加入自己的記錄。如果你想在你的表中的樹形結構,那麼你需要(id, parent_id, ...)的領域,並加入對subject.parent_id = parent.id

1

您的查詢應該是

SELECT 
`subject`. `id`, 
`subject`.`subject` AS `subject_name`, 
`parent`.`subject` AS `parent_name` 
FROM 
`subjects` AS `subject` 
LEFT JOIN 
`subjects` AS `parent` 
ON 
`parent`.`id` = `subject`.`parent_id`;