表连接 - 如果一个表没有相应的记录,则返回所有记录

时间:2014-09-29 01:46:17

标签: mysql sql

我有一个连接查询,即使specimen_image_lookup.specimen_fk没有specimen.specimen_pk的相应记录,我也要返回所有记录:

SELECT * FROM specimen, topography_index, morphology, specimen_image_lookup, image 
WHERE 
SUBSTRING(specimen.topography_index, 2, 2) = topography_index.topography_index_code 
AND 
morphology.morphology_code = specimen.snop_code 
AND 
specimen_image_lookup.specimen_fk = specimen.specimen_pk AND image.image_pk = specimen_image_lookup.image_fk 
AND 
topography_index.topography_index_code IN('".implode("','",$sub_cat)."') 
GROUP BY 
specimen.specimen_pk

即使samples_image_lookup没有samples.specimen_pk的记录,如何修改此查询以返回所有记录?

1 个答案:

答案 0 :(得分:2)

您必须对该表以及图像表使用外部联接,因为您在图像表和该表之间有一个连接,您可能没有相关记录:

select *
  from specimen
  join topography_index
    on substring(specimen.topography_index, 2, 2) =
       topography_index.topography_index_code
  join morphology
    on morphology.morphology_code = specimen.snop_code
  left join specimen_image_lookup
    on specimen_image_lookup.specimen_fk = specimen.specimen_pk
  left join image
    on image.image_pk = specimen_image_lookup.image_fk
 where topography_index.topography_index_code in ('".implode("', '",$sub_cat)."')

通常,对所有连接条件使用join子句也是一个好主意。

我删除了您的GROUP BY子句,因为您在SELECT列表中没有聚合函数,并且语法错误,在除MySQL以外的任何数据库中都会返回错误。如果要聚合某些内容,则只使用GROUP BY子句。