2012-11-14 54 views
1

我有一個表5列 - col1,co12,...我有5個搜索參數搜索每列。我需要編寫一個mySQL查詢來返回所有匹配的結果。如果我沒有爲搜索參數提供值,它將被忽略。mySQL變量搜索空變量

我有這個,但它不工作

select * from tableA 
where ((col1 IS NULL AND srch1 IS NULL) OR (col1 like srch1)) 
and ((col2 IS NULL AND srch2 IS NULL) OR (col2 like srch2)) 
etc... 

回答

0
Select * from tableA where 
col1 like '%' + Coalesce(srch1,col1) + '%' and 
col2 like '%' + Coalesce(srch2,col2) + '%' 
0

我認爲是「不工作」你的意思是你的條件like部分不能正常工作。

這將是因爲你必須用%字符包裝你的搜索字符串以形成一個「喜歡」的搜索詞。試試這個:

select * from tableA 
where ((col1 IS NULL AND srch1 IS NULL) OR col1 like concat('%', srch1, '%')) 
and ((col2 IS NULL AND srch2 IS NULL) OR col2 like concat('%', srch2, '%')) 
etc... 


你是八九不離十!

0

通過使每個條件與其自身在ORS中並首先對零進行測試,這將預先限定條件並忽略另一半。如果有一個值,那麼它會針對相應的列進行測試。現在,這就是說,如果你確實需要一個「LIKE」限定符,那麼你可能需要預期或者在'%'上加上通配符匹配。

select 
     A.* 
    from 
     tableA A 
    where 
      (srch1 is null OR col1 like srch1) 
     AND (srch2 is null OR col2 like srch2) 
     AND (srch3 is null OR col3 like srch3) 
     AND (srch4 is null OR col4 like srch4) 
     AND (srch5 is null OR col5 like srch5) 

所以,如果你只提供srch3參數,那麼答案將解釋爲

where 
     TRUE 
    and TRUE 
    and col3 like srch3 
    and TRUE 
    and TRUE 

自SRCH?如果爲null,則首先爲true,然後忽略該測試的其餘部分。