2017-03-01 43 views
0

我有以下的Mysql查詢,我想添加一個計數器,顯示每行匹配的數量。MySQL多個像條件和添加到計數器時匹配

select id, selection 
FROM tablename 
WHERE (selection LIKE '%13%' OR selection LIKE '%17%' OR 
     selection LIKE '%19%' OR selection LIKE '%73%') 

最終目標是輸出每行的計數並過濾結果只有2個或更多匹配。

以下是表中的一個樣本數據:

ID - 選擇

1 - 3,5,19,23

2 - 13,17,34,45

我正在尋找的是返回結果集的所有行,至少有2個數字,其中有多少匹配

例如:

ID - 選擇 - 計數

4 - 13,17,26,56 - 2

56 - 13,17,19,40 - 3

105 - 12,17,24, 73 - 2

有人可以幫我修改這個具體的查詢嗎? 謝謝:)

+1

添加一些示例表數據和預期結果。 (你可以通過只有兩個不同的例如13和17來最小化你的問題。) – jarlh

回答

0

我想你期待這樣的代碼


Select id, COUNT(*) as count from (select id,selection 
FROM Test 
WHERE (selection LIKE '%13%' OR selection LIKE '%17%' OR 
     selection LIKE '%19%' OR selection LIKE '%73%') 
     group by id,selection) t group by id having COUNT(*) >= 2 

0

你根本的問題是要存儲號碼清單中的字符串。這只是錯誤的,錯誤的,錯誤的,錯誤的,錯誤的。爲什麼?

  • 數字應該存儲爲數字而不是字符串。
  • SQL的字符串功能很差。
  • SQL有一個偉大的數據類型來存儲列表。這是一個叫做表格。使用一個!
  • 引擎無法很好地優化查詢。
  • 如果這些是ids到另一個表中,那麼你應該有適當的,聲明的外鍵關係。

有時其他人們做出真的很糟糕的設計決定。而且,我們最終陷入了困境。對於這種情況,MySQL有一個方便的函數叫做find_in_set()。你可以使用它:

select id, selection 
from tablename 
where find_in_set(13, selection) > 0 or 
     find_in_set(17, selection) > 0 or 
     find_in_set(19, selection) > 0 or 
     find_in_set(73, selection) > 0 ; 

如果你想測試多個匹配,你可以計數匹配的數量。通過將布爾表達式視爲整數,MySQL使這變得簡單:

select id, selection 
from tablename 
where ((find_in_set(13, selection) > 0) + 
     (find_in_set(17, selection) > 0) + 
     (find_in_set(19, selection) > 0) + 
     (find_in_set(73, selection) > 0) 
    ) >= 2