2013-05-04 104 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