2017-10-16 35 views
2

假設我有一個表如何運行替代WHERE條件,如果行是零

+-------------+ 
| id | name | 
+-------------+ 
| 1 | xabx | 
| 2 | abxd | 
| 3 | axcd | 
| 4 | azyx | 
| 5 | atyl | 
| 6 | aksd | 
| 7 | baabc| 
| 8 | aabcd| 
+-------------+ 

首先我得的數據,如果比賽第一一些字符,如:

如果name = aab

然後必須運行select * from table where name like 'aab%'

然後返回

+-------------+ 
| 8 | aabcd | 
+-------------+ 

這execatlly我想

,但如果我只有abc

那麼上面的查詢返回0

然後我必須從像中搜索:

select * from table where name like '%abc%'

那麼它將返回是替代

+-------------+ 
| 7 | baabc| 
| 8 | aabcd| 
+-------------+ 

我有關於MySQL沒有多少知識有任何疑問可以做到一樣,如果第一where條件不具備行,然後運行其中的替代條件

我試過這個,但沒有按我的要求工作。

select * from table where name like 'abc%' or name like '%abc%'

fiddle

由於事先

+0

是否有任何理由不能每次都使用'%match%'? – Aknosis

+0

上次查詢的輸出有什麼問題? –

+0

表名缺失。 –

回答

0

這是一個可能的解決方案:

左接合表上本身,其中表最初由更包容%bx%並過濾那麼加入將被更嚴格的bx%過濾。

這使您可以使用加入了名稱,如果它存在,但如果沒有恢復到原來的:

SELECT t1.id, IF(t2.name IS NULL, t1.name, t2.name) name 
FROM test t1 
LEFT JOIN test t2 ON t2.id = t1.id AND t1.name like 'bx%' 
WHERE t1.name LIKE '%bx%' 

這可能/可能不取決於大小或數據集是理想的。

0

COUNT檢查可能工作

select * 
from table 
where name like 'aab%' or 
     ((select count(*) from table where name like 'aab%') = 0 and name like '%abc%') 

我想,這將是計算計數值到一個變量第一,然而,優化程序可能無論如何承認獨立的子查詢,一旦運行它是個好主意。

+0

顯示錯誤看看:http://rextester.com/TKZAT61150 – User97798

+0

@ User97798對不起,只是缺少'where'... –

1

這是屬於你想要的結果:

select *from t 
where (case 
      when name like 'abc' then 1 
      when name like 'bc%' then 1 
      when name like '%bc' then 1 
      when name like '%bc%' then 1  
      else null 
      end) 
order by name 
    limit 1; 

我只是把所有的組合爲條件。 你可以互相交換順序或移除不必要的情況。 limit 1只有一行可見,無論哪個條件滿足。

這是您的小提琴的答案。 Check it out

希望它有幫助!

+0

http:// rextester .com/MAN24628 –

+0

它按預期工作嗎? –

+0

如果上述答案解決/有助於解決您的問題,那麼請接受它作爲答案和/或upvote答案。這對未來的訪問者會非常有幫助。 –