MySQL查询中的多个内部联接失败

时间:2016-01-11 12:54:38

标签: mysql inner-join

如果{string}从查询中引出,但如果我包含它则失败,则以下情况有效。到目前为止,大多数帖子上都有多个内连接显然有效,但实际情况并非如此,我们会对任何有关问题的反馈表示赞赏。

perl

好的做了一些测试,并注意到如果species_synonyms_tbl表与species_tbl表无关,它将不会返回结果,因此它对事实的约束期望关系id存在

$ touch -t "03202009" file
$ perl -sle '@stat=stat($filename); print "$stat[8]"' -- -filename=file
1458504540

由于

1 个答案:

答案 0 :(得分:0)

这是因为您正在对species_common_names_tblspecies_synonyms_tbl表进行内部联接,因此您必须在两个表上都有匹配的记录 - 同义词表中提供的数据中的唯一记录是物种2。

尝试将连接更改为外连接,如下所示:

SELECT DISTINCT species_tbl.* FROM species_tbl     
left join species_common_names_tbl 
        ON species_tbl.id = species_common_names_tbl.species_id      
left join species_synonyms_tbl ON species_tbl.id = species_synonyms_tbl.species_id
WHERE LOWER(species_tbl.keywords) LIKE LOWER('%Plain Rain Frog%') OR 
      LOWER(species_common_names_tbl.common_name) LIKE LOWER('%Plain Rain Frog%') OR 
      LOWER(species_synonyms_tbl.syn_genus) LIKE LOWER('%Plain Rain Frog%') OR 
      LOWER(species_synonyms_tbl.syn_sub_genus_name) LIKE LOWER('%Plain Rain Frog%') OR 
      LOWER(species_synonyms_tbl.syn_species_epithet) LIKE LOWER('%Plain Rain Frog%') 

SQLFiddle here

编辑,在确认性能问题后 - 以下似乎对更大的数据集表现更好:

SELECT DISTINCT species_tbl.* FROM species_tbl     
left join (select distinct species_id from species_common_names_tbl 
           where LOWER(common_name) LIKE LOWER('%Plain Rain Frog%')) scn
        ON species_tbl.id = scn.species_id      
left join (select distinct species_id from species_synonyms_tbl 
           where LOWER(syn_genus) LIKE LOWER('%Plain Rain Frog%') OR 
                 LOWER(syn_sub_genus_name) LIKE LOWER('%Plain Rain Frog%') OR 
                 LOWER(syn_species_epithet) LIKE LOWER('%Plain Rain Frog%') ) ss
        ON species_tbl.id = ss.species_id
WHERE LOWER(species_tbl.keywords) LIKE LOWER('%Plain Rain Frog%') OR 
      scn.species_id is not null OR 
      ss.species_id is not null

SQLFiddle here