2014-02-11 33 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