2017-03-05 48 views
0

我有2個表,顯示如下簡化:左加入與OR子句

Table 1: | id | somedata | checkcode 
Table 2: | id | somedata | checkcode1 | checkcode2 

我需要左加入第二個,其中checkcode1 OR checkcode2就像註冊碼。我試圖做出兩個不同的左連接,但這不起作用,因爲它包含了兩倍的數據。

我需要的是這樣的:

Select * from Table1 as t1  
LEFT JOIN Table2 as t2 
on t1.checkcode = (t2.checkcode1 OR t2.checkcode2)  

這可能嗎?

+2

你嘗試簡單明確寫入的條件? 'Select * from Table1 as t1 LEFT JOIN Table2 as t2 on(t1.checkcode = t2.checkcode1 OR t1.checkcode = t2.checkcode2)' –

+0

yay this worked!如果你把它作爲回答,我接受你,因爲你是第一個。謝謝! – sharkyenergy

+0

這裏有一條線索:IN() – Strawberry

回答

1

嘗試這樣,

Select * from Table1 as t1 
LEFT JOIN Table2 as t2 on t1.checkcode = t2.checkcode1 OR t1.checkcode = t2.checkcode2 
2

試試這個,你是說 「我需要離開加入了第二個地方checkcode1 OR checkcode2是註冊碼」

SELECT * 
FROM Table1 
INNER JOIN Table2 ON CONCAT(Table2.checkcode1,Table2.checkcode2) LIKE CONCAT('%', Table1.checkcode, '%') 

編輯

select * from Table1 as t1 
LEFT JOIN Table2 as t2 on t1.checkcode IN(t2.checkcode1 ,t2.checkcode2) 
+0

你是對的,類似的詞是我的錯。我需要它是確切的。抱歉。 sahar bental的解決方案就像一個魅力。 – sharkyenergy

1

你可以試試下面的查詢:

SELECT t1.*, t2.* 
FROM table1 t1 LEFT JOIN table2 t2 ON (t1.checkcode LIKE CONCAT('%', t2.checkcode1, '%') 
OR t1.checkcode LIKE CONCAT('%', t2.checkcode2, '%')); 

您可以= t2.checkcode2取代LIKE CONCAT('%', t2.checkcode2, '%')如果要進行精確的字符串比較。

0

你也可以試試這種方式來執行你的LEFT JOIN

Select * from Table1 as t1 LEFT JOIN Table2 as t2 on t1.checkcode IN (t2.checkcode1,t2.checkcode2); 

支票本上SQL Fiddle