MySQL嵌套连接

时间:2013-05-04 02:41:50

标签: mysql sql join relational-database

我正在存储生态调查的数据。在每个采样点,收集多个个体并确定物种名称,属名和姓氏。

数据库中的表格如下:

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仅链接到genus表中的一条记录。

4)tab_genus:找到的所有属的列表。键(唯一ID)是tab_genus.id_genus。通过tab_genus.ref_id_family

链接到系列表中的一条记录

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

我想要做的是列出在每个站点中找到的个体,列出他们的物种名称,属和家庭。我希望这样的东西能起作用:

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 个答案:

答案 0 :(得分: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