Mysql将两个值匹配为列表

时间:2012-02-28 14:21:30

标签: mysql database phpmyadmin

我有两个表,我想匹配这样的记录

SELECT * FROM records1
WHERE records1.set IN (SELECT records2.p
FROM `records2`
WHERE rcords2.id=1200 )

我只用这个查询测试它:

SELECT (records2.p)
FROM `records2`
WHERE rcords2.id=1200

给出结果

p
========
14, 12, 80

还有像这样的records1.set值

set
=============
80, 20, 60

它与原因不符?

1 个答案:

答案 0 :(得分:0)

您的不同设定值的数量是有效的。所以这应该有效:

SELECT * FROM records1, records2
WHERE (rcords2.id=1200) and (
    ((FIND_IN_SET('12', records1.set) > 0) and (FIND_IN_SET('12', records2.p) > 0)) or
    ((FIND_IN_SET('14', records1.set) > 0) and (FIND_IN_SET('14', records2.p) > 0)) or
    ((FIND_IN_SET('60', records1.set) > 0) and (FIND_IN_SET('60', records2.p) > 0)) or
    ((FIND_IN_SET('80', records1.set) > 0) and (FIND_IN_SET('80', records2.p) > 0)) or
    ...
)

如果两个表的集合以相同的方式定义(以相同的顺序),也可以进行二进制操作:

select * from records1, records2
where (rcords2.id=1200) and (records1.set & records1.set);

仅当两个列都属于集合类型('12','14','60','80',...)时才有效

如果它是字符串字段中的逗号分隔列表,则sql语句可能如下所示:

SELECT * FROM records1, records2
WHERE (records2.id=1200) and (
(CONCAT(",", records2.p, ",") like CONCAT("%,", substring_index(substring_index(records1.set, ',', 1), ',', -1), ",%")) or
(CONCAT(",", records2.p, ",") like CONCAT("%,", substring_index(substring_index(records1.set, ',', 2), ',', -1), ",%")) or
(CONCAT(",", records2.p, ",") like CONCAT("%,", substring_index(substring_index(records1.set, ',', 3), ',', -1), ",%")) or
(CONCAT(",", records2.p, ",") like CONCAT("%,", substring_index(substring_index(records1.set, ',', 4), ',', -1), ",%")) or
...
(CONCAT(",", records2.p, ",") like CONCAT("%,", substring_index(substring_index(records1.set, ',', N), ',', -1), ",%"))
)

如果字符串字段是varchar(X),而字段中的可能值少于X / 2,那么在我的SQL语句中用X / 2替换N.