MySQL - 使用IF条件连接表

时间:2014-09-29 02:47:19

标签: mysql sql

我想要使用IF条件修改以下查询:

if(specimen.snop_axis = 'M', join morphology
    on morphology.morphology_code = specimen.snop_code, join functions on functions.functions_code = specimen.snop_code)

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
  join functions
    on functions.functions_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 specimen.specimen_pk = '$specimen'

如何修改此查询以合并此if条件?也就是说,IF语句需要替换:

join morphology
    on morphology.morphology_code = specimen.snop_code
  join functions
    on functions.functions_code = specimen.snop_code

2 个答案:

答案 0 :(得分:3)

specimen.snop_axis的逻辑(等于或不等于)加入到两个表的连接条件中,如下所示:

SELECT
      *
FROM specimen
      JOIN topography_index
                  ON SUBSTRING(specimen.topography_index, 2, 2) =
                        topography_index.topography_index_code
      LEFT JOIN morphology
                  ON specimen.snop_axis = 'M' AND morphology.morphology_code = specimen.snop_code
      LEFT JOIN functions
                  ON specimen.snop_axis <>'M' AND functions.functions_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 specimen.specimen_pk = '$specimen'
;

答案 1 :(得分:0)

SQL查询只能返回一组固定的列。您可以使用动态SQL执行所需操作,但不能使用常规SQL查询。

您可以添加额外的列,并在样本不匹配时将它们设为NULL

from子句将继续:

left join
image
on image.image_pk = specimen_image_lookup.image_fk left join
morphology
on morphology.morphology_code = specimen.snop_code and specimen.snop_axis = 'M' left join
. . . 

我不太确定你的join是如何继续的。但是如果包含额外条件,那么非匹配样本的列将具有NULL值。