用于匹配数据库数组的mysql查询

时间:2013-10-03 09:28:23

标签: mysql sql database

我有一个简单的数据库表,它具有以下结构:

Teams       Id_1           Id_2            Id_3 

team_1       A              B                C

team_2       A              B                D

team_3       E              F                D

team_4       X              null            null

team_5       D              A                B

现在我有一个字符串ID的示例数组,其值为:A B.我想根据此数据点与数据库的最大匹配来选择团队/团队,例如,匹配的结果应该给我team_1,team_2和team_5作为输出。在mysql上执行此查询的有效方法是什么?提前致谢。

2 个答案:

答案 0 :(得分:1)

试试这个。获取ID字段并填充空格(分隔符)。 Pad搜索字符串也带有空格。然后检查是否可以在填充的搜索字符串中找到填充的ID。

Select *
From Tbl
Where ' ' + ID_1 + ' ' in ' ' + SearchStr + ' '
   Or ' ' + ID_2 + ' ' in ' ' + SearchStr + ' '
   Or ' ' + ID_3 + ' ' in ' ' + SearchStr + ' '

答案 1 :(得分:1)

假设你想要那些匹配最佳的(所以如果搜索[DZ]它会找到带有D的3个项目,但是因为没有包含Z的东西会被忽略,那么可能是这样的(未经测试): -

SELECT *
FROM SomeTable
CROSS JOIN
(
    SELECT MAX(IF(FIND_IN_SET(ID_1, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(ID_2, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(ID_3, REPLACE("A B", " ", ",")) > 0 > 0, 1, 0)) AS MaxCount
    FROM SomeTable
    WHERE FIND_IN_SET(ID_1, REPLACE("A B", " ", ",")) > 0
    OR FIND_IN_SET(ID_2, REPLACE("A B", " ", ",")) > 0
    OR FIND_IN_SET(ID_3, REPLACE("A B", " ", ",")) > 0
) Sub1
WHERE IF(FIND_IN_SET(SomeTable.ID_1, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(SomeTable.ID_2, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(SomeTable.ID_3, REPLACE("A B", " ", ",")) > 0 > 0, 1, 0) = Sub1.MaxCount

请注意,如果传递的列表以逗号分隔,则可以避免使用所有替换语句。