2016-06-11 61 views
1

我要加入兩個表上依賴於一定條件的外地加盟:條件在SQL

select * from table1 join table2 on table1.$variable = table2.id 

$variable = table1.id1 is not null ? table1.id1 : table1.id2 

我能做到這一點?

回答

1

您可以使用條件或JOIN:

select * from table1 join table2 on 
    (table1.id1 IS NOT NULL AND table1.id1 = table2.id) 
    OR 
    (table1.id1 IS NULL AND table1.id2 = table2.id) 
1
select * 
from table1 join table2 
    on case when table1.id1 is not null then table1.id1 else table1.id2 end = table2.id 
1
`select * from table1,table2 where ifnull(table1.id1,table1.id2)=table2.id` 

如果IFNULL第一值爲null,則它使用了第二個。

再見

+0

會更好,當你切換到標準SQL的'COALESCE(table1.id1,表1。 ID2)' – dnoeth

2

有幾種方法來解決這個

IF() 
IFNULL(), 
COALESCE(), 
CASE 

使用如果使用IFNULL

SELECT * FROM table1 JOIN table2 ON 
IFNULL(table1.id1, table1.id2)=table2.id; 

SELECT * FROM table1 JOIN table2 ON 
IF(table1.id1 IS NOT NULL,table1.id1, table1.id2)=table2.id; 

使用COALESCE

SELECT * FROM table1 JOIN table2 ON 
COALESCE(table1.id1, table1.id2)=table2.id; 

使用案例

SELECT * FROM table1 JOIN table2 ON 
(CASE 
WHEN table1.id1 IS NULL THEN table1.id2 
ELSE table1.id1 
END) = table2.id; 

參考http://sqlfiddle.com/#!9/8076eb/4