2014-02-11 31 views
-1

我只想獲得所有接收方id匹配的記錄,但查詢中的find_in_setIN運算符返回包含任何id的所有記錄。如何匹配數據庫中所有逗號分隔的字符串?

我希望只獲得匹配我數據庫中所有all_recipients列的記錄。

例如,我想只能用PID = 6在下列情況下,戰績:

我有以下查詢:

SELECT * FROM `conf_event_message_recipients` WHERE receiver IN (6622,6607) AND event_id = 46 

和數據庫記錄:

pid mid seq  receiver  all_recipients  event_id status 
8 127 9  6622   6607,6622,6624  46   2 
6 127 9  6622   6607,6622   46   2 
9 127 9  6622   6607,6622,6624  46   2 

我該如何做到這一點?

+0

值嘗試SELECT * FROM'conf_event_message_recipients'其中pid = 6 – krishna

+0

無我有隻有接收器id和我想要pid – Naeem

+0

嘗試SELECT * FROM conf_event_message_recipients WHERE receiver LIKE'%6607,6622%' – krishna

回答

1

使用正常的相等比較:

SELECT * 
FROM conf_event_message_recipients 
WHERE all_recipients = '6607,6622' 

,或者如果你不能保證順序:

SELECT * 
FROM conf_event_message_recipients 
WHERE CHAR_LENGTH(all_recipients) - CHAR_LENGTH(REPLACE(all_recipients, ',', '')) = 1 
AND FIND_IN_SET('6607', all_recipients) 
AND FIND_IN_SET('6622', all_recipients) 

的第一個條件計算逗號的字段中的數字,這是一個都不能少比值的數量。然後剩餘的條件檢查每個要求的值是否在現場。

如果表很大,這是一個非常低效的查詢。你需要規範化你的模式來解決這個問題。

+0

如果DB中的值爲6622,6607,則這將不起作用。 –

+0

哪裏適用於all_recipients或接收方? – Naeem

+0

它不工作。 – Naeem

2

這並不美觀,但是當您將列表存儲在字段中而不是使用關聯/聯結表時,會發生這種情況。你真的應該修復數據結構。

以下方法通過對每個值使用find_in_set()來計算字符串中匹配的數量。然後,它比較所述串中的項數,使用特技其中每個逗號由兩個字符替換,取長度,減去初始長度和加入一種:

SELECT * 
FROM `conf_event_message_recipients` 
WHERE (find_in_set(6622, all_recipients) > 0 + 
     find_in_set(6607, all_recipients) > 0 
    ) = (length(replace(all_recipients, ',', ',,')) - length(all_recipients) + 1) 
WHERE event_id = 46; 

編輯:

有是另一種方法,這也是不漂亮:

select * 
from conf_event_message_recipients 
where replace(replace(replace(concat(',', all_recipients, ',', ',6622,', '', 
          ) ',6607,', '' 
        ), ',', '' 
      ) = '' and 
     event_id = 46; 

也就是說,用空字符串替換每個ID,然後刪除逗號,並確保有一無所有。額外的逗號是爲了防止「660」在替換中匹配「6607」。

+0

Man ...這絕對不是很漂亮!更不用說大數據可能出現的過熱。他應該明確修復數據集! +1爲您的答案:) – tftd

1

您可以使用下面的查詢:

SELECT * FROM `conf_event_message_recipients` WHERE all_recipients LIKE '%6622%' AND all_recipients LIKE '%6607%' AND LENGTH(all_recipients) = 9 AND event_id = 46 

變化LENGTH(all_recipients)按照元素的數量all_recipients