2013-05-04 106 views
3

我正在存儲生態調查的數據。在每個採樣地點,收集多個個體並確定物種名稱,屬名和姓氏。MySQL嵌套連接

在數據庫中的表如下:

1)tab_indiv:存儲關於每個個體中發現的數據。每個人只喜歡物種表(tab_indiv.ref_id_species,個體屬於的物種)中的一條記錄,並且只有一個記錄在網站表(tab_indiv.ref_id_site,個人從中抽樣的網站)中。

2)tab_site:調查發生的所有網站的列表。密鑰(唯一ID)是tab_site.id_site

3)tab_species:找到的所有物種的列表。密鑰(唯一ID)是tab_species.id_species。通過tab_species.ref_id_genus鏈接到屬性表中的僅一條記錄。

4)tab_genus:找到的所有屬的列表。密鑰(唯一ID)是tab_genus.id_genus。通過tab_genus.ref_id_family

5)tab_family:找到的所有家族的列表。密鑰(唯一ID)是tab_family.id_family。

我想要做的是列出每個網站中發現的個人,plust他們的物種名稱,屬和家庭。我希望這樣的事情可以工作:

SELECT 
    tab_indiv.ref_id_species AS 'Species Name', 
    tab_species.id_species AS 'Species Name 2', -- Just to check if I got the joins ok 
    tab_genus.id_genus AS 'Genus Name', 
    tab_family.id_family AS 'Family Name' 
    tab_site.id_site AS 'Site Num' 
FROM (tab_site 
    LEFT JOIN tab_indiv 
     ON tab_site.id_site = tab_indiv.ref_id_site 
    LEFT JOIN tab_species 
     ON tab_indiv.ref_id_species = tab_species.id_species 
    LEFT JOIN tab_genus 
     ON tab_species.ref_id_genus = tab_genus.id_genus 
    LEFT JOIN tab_family 
     ON tab_genus.ref_id_family = tab_family.id_family); 

...但它不起作用。如果每個網站有不止一個家庭,個人名單就會重複出現,並且所有個人都與所有家庭合併,但每個人只能屬於一個家庭。當我添加第三個LEFT JOIN時,問題就出現了。

理想我會得到這樣的事情

sp1 | gen1 | fam1 | site1 
sp2 | gen1 | fam1 | site1 -- sp1 and sp2 belongs to gen1  
sp3 | gen2 | fam2 | site1 
sp4 | gen3 | fam2 | site1 -- gen1 and gen2 belongs to fam2 

相反,我所得到的是

sp1 | gen1 | fam1 | site1 -- ok! 
sp2 | gen1 | fam1 | site1 -- ok! 
sp1 | gen1 | fam2 | site1 -- notice that sp1 and gen1 does not belong to fam2 
sp2 | gen1 | fam2 | site1 -- notice that sp2 and gen1 does not belong to fam2 
sp3 | gen2 | fam1 | site1 -- notice that sp3 and gen2 does not belong to fam1 
sp4 | gen3 | fam1 | site1 -- notice that sp4 and gen3 does not belong to fam2 
sp3 | gen2 | fam2 | site1 -- ok! 
sp4 | gen3 | fam2 | site1 -- ok! 

任何想法?歡迎您的建議,並表示感謝!

+1

什麼不起作用?它顯示你不期望的結果?顯示你想要得到什麼和你得到什麼 – sashkello 2013-05-04 02:44:16

+0

請提供基於它的樣本數據和所需的輸出。 – peterm 2013-05-04 02:46:10

+0

現在,查詢完全按照您的要求進行。目前還不清楚是什麼問題。 – sashkello 2013-05-04 02:52:38

回答

0

試試這個,你並不真正需要的所有表和LEFT JOIN是沒有用的,以及:

SELECT 
    tab_indiv.ref_id_species, 
    tab_species.ref_id_genus, 
    tab_genus.ref_id_family, 
    tab_indiv.ref_id_site 
FROM 
    tab_indiv 
    JOIN tab_species ON tab_indiv.ref_id_species = tab_species.id_species 
    JOIN tab_genus ON tab_species.ref_id_genus = tab_genus.id_genus