2014-09-29 92 views
0

我有以下查詢,我想用IF條件像修改:MySQL的 - 連接表與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語句需要替換:

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

回答

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' 
; 
+0

+1,您可以通過一分鐘 – radar 2014-09-29 03:03:38

+0

@Used_By_Already打我...美麗!非常感謝! – IlludiumPu36 2014-09-29 03:06:18

+0

您需要添加JOIN後左手形態... – IlludiumPu36 2014-09-29 03:08:43

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 S如何繼續。但是,如果您包含額外條件,則不匹配的樣本將具有列的值NULL