2010-11-13 92 views
99

我有這個MySQL查詢。MySQL喜歡多個值

我有這個內容

sports,shopping,pool,pc,games 
shopping,pool,pc,games 
sports,pub,swimming, pool, pc, games 

爲什麼會出現這種類似的查詢不起作用數據庫字段? 我需要與運動或酒吧或兩個領域?

SELECT * FROM table WHERE interests LIKE ('%sports%', '%pub%') 

回答

89

(a,b,c)列表僅適用於in。對於like,你必須使用or

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%' 
6

您的查詢應該是SELECT * FROM `table` WHERE find_in_set(interests, "sports,pub")>0

我的理解是,你存儲在你的表,這是一個誤解的一個領域的利益。你應該明確地有一個「興趣」表。這樣做的

+2

我認爲它應該是'SELECT * FROM table WHERE find_in_set(interest,'sports,pub')',但是這種技術在大多數情況下可能會勝過正則表達式。 – 2017-09-14 04:02:06

+0

你是對的。我編輯了我的答案。 – 2018-01-23 09:54:42

234

比較快的方式:

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%' 

是這樣的:

WHERE interests REGEXP 'sports|pub' 

發現這個解決方案在這裏:http://forums.mysql.com/read.php?10,392332,392950#msg-392950

更多REGEXP這裏:http://www.tutorialspoint.com/mysql/mysql-regexps.htm

+28

+1,但運行時速度並不快,但按鍵速度更快。 – Johan 2011-09-27 09:39:48

+0

如果你傳遞一個未知數量的關鍵字作爲字符串(a | b | c ...),那麼如果你想要像這樣使用正則表達式,唯一的方法就是使用正則表達式。 – frequent 2012-06-21 12:53:19

+0

你知道這是否可以通過子查詢完成嗎?假設我有一列我需要搜索的詞,我如何用一個子查詢替換'sports | pub'? – AdamMc331 2014-10-25 19:25:20

3

唐「T忘了,如果你的AND參數

篩選後,使用此功能使用括號:

WHERE id=123 and(interests LIKE '%sports%' OR interests LIKE '%pub%') 
25

爲什麼不試試REGEXP。試着這樣說:

SELECT * FROM table WHERE interests REGEXP 'sports|pub' 
+1

這真的很不錯。學到了新東西。謝謝,, – amrodelas 2016-06-20 09:35:06

+0

這應該是被接受的答案。 – Mark 2016-08-09 19:50:12

+0

感謝馬克,但他們已經接受了另一個答案:) – 2016-08-10 07:02:51

1

像@Alexis Dufrenoy建議,查詢可能在manualSELECT * FROM `table` WHERE find_in_set('sports', interests)>0 OR find_in_set('pub', interests)>0

更多信息。