2013-05-18 42 views
0

對場選擇我有如下表:通過在MySQL

+-------+-------+-------------+ 
|column1|column2| column3 | 
+-------+-------+-------------+ 
| 2 | 4 | row 1 | < compare with this 
| 4 | 3 | row 2 | + < here`s 4 
| 5 | 2 | row 3 | + < here`s 2 
| 1 | NULL | row 4 | - < no 4 or 2 
| 5 | 6 | row 5 | - < no 4 or 2 
| NULL | 2 | row 6 | + < here`s 2 
+-------+-------+-------------+  

的問題是如何找到所有的行,即至少包含一個搜索值。例如,我需要找到像第一行那樣的行,所以我要查找前兩列有2或4的行。所以我的輸出應該是2,3和6行。我不需要找到NULL值。

請指教。

+1

的問題是我們不知道哪一行是第一個。請記住,服務器隨機插入行。我認爲你需要首先搜索一條記錄,然後比較表中所有行的結果。唯一一次你可以得到第一行是**來過濾記錄**,例如'SELECT * FROM tableName WHERE column3 ='row 1'' –

+0

我的歉意,我用第一行僅供參考。我會知道要搜索的值。感謝您的迴應。 –

回答

1
select * 
from foo 
where ( 2 in (col1, col2) 
     or 4 in (col1, col2)) 
and (col3 <> 'row 1') 

SQL小提琴例如:http://sqlfiddle.com/#!2/7fd81/5

或者更動態得到它:

select t.* 
from foo t 
join (
    select col1, col2 
    from foo 
    where col3 = 'row 1' 
) r1 on r1.col1 = t.col1 
    or r1.col2 = t.col2 
    or r1.col1 = t.col2 
    or r1.col2 = t.col1 
where col3 <> 'row 1' 

SQLFiddle:http://sqlfiddle.com/#!2/7fd81/3

+0

就是這樣。謝謝。 –

+0

哦,只是試圖執行。如果我們在row1中有NULL值,該怎麼辦? MySQL報告錯誤,當得到空的空間時:_ ..或_ IN(col1,col2).._是否有任何解決方法,或者它會更好地過濾它在PHP? –

+0

@VitalyMirsky:嘗試第二條語句,那將更好地處理空值 –