2014-10-04 134 views
0

我嘗試在mysql連接中建立一個條件'on子句'。mysql - 在mysql連接條件'on子句'

如果field1不爲空,則應在'on claus' 中使用,但如果爲空,則應使用field2。

SELECT * FROM table1 
JOIN table2 

IF (field1!='') THEN (
    ON table1.field1 = table2.field1 
    AND table1.field3 = table2.field3 
    ) 
ELSE (
    ON table1.field2 = table2.field2 
    AND table1.field3 = table2.field3 
    ) 
END IF 

任何想法,如果這是可能的如何可以完成?

編輯: 我忘了解釋這兩個表都包含空字段,我試圖防止mysql使用這些字段進行連接,因爲這給出了非常多的連接,所以我的想法應該更像這樣:

SELECT * FROM table1 
JOIN table2 

IF (table1.field1!='' AND table2.field1!='') THEN (
    ON table1.field1 = table2.field1 
    AND table1.field3 = table2.field3 
    ) 
ELSE (
    ON table1.field2 = table2.field2 
    AND table1.field3 = table2.field3 
    ) 
END IF 

回答

3

試試這個:

SELECT * FROM table1 t1 
LEFT JOIN table2 t2 
LEFT JOIN table2 t3 
on t1.Field1=t2.Field1 and t1.Field3=t2.Field3 
on t1.Field2=t3.Field2 and t1.Field3=t3.Field3 

然後使用壽從表2或表3選擇該領域的條件。

希望這可以幫助你。

編輯

要選擇合適的現場使用這樣的:

SELECT t1.*, IF(t2.field1 is null, t3.field1, t2.Field1) as Field1 
+0

條件應放置在where子句中,是對的嗎? – user3304232 2014-10-04 14:22:20

+0

在選擇。我編輯我的答案 – ericpap 2014-10-04 14:44:03

+0

目前我在'on子句'中獲得「未知列't2.Field1'」 – user3304232 2014-10-04 15:05:57

0

你應該考慮將你的INNER JOIN爲已經在其他的答案中所示一樣

SELECT * FROM table1 t1 
    LEFT JOIN table2 t2 
    ON t1.field1 = t2.field1 AND t1.field3 = t2.field3 
    LEFT JOIN table2 t22 
    ON t1.field2 = t22.field2 AND t1.field3 = t22.field3 

你一個LEFT JOIN還可以嘗試下面的東西

SELECT t1.* 
FROM table1 t1 
    JOIN table2 t2 
    ON t1.field1 = t2.field1 AND t1.field3 = t2.field3 
     OR t1.field2 = t2.field2 AND t1.field3 = t2.field3 
0

我認爲你可以做這樣的事情:

SELECT * FROM table1 
JOIN table2 ON 
    (
     (table1.field1 = '' AND table1.field2 = table2.field2 AND table1.field3 = table2.field3) 
     OR 
     (table1.field1 != '' AND table1.field1 = table2.field1 AND table1.field3 = table2.field3) 
    ) 

(注:我不知道如何有效地或以其他方式這種方式)