如何使用列中的逗号分隔字符串作为MySQL IN语句的值

时间:2014-08-21 14:29:00

标签: mysql sql

我有两张桌子,我想离开加入。

DROP TABLE IF EXISTS test_1;
CREATE TABLE test_1 (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(32) NOT NULL,
  description varchar(255) NOT NULL,
  PRIMARY KEY (id)
) ;

-- ----------------------------
-- Records of test_1
-- ----------------------------
INSERT INTO test_1 VALUES ('1', 'Item A', 'Description for Item A');
INSERT INTO test_1 VALUES ('2', 'Item B', 'Description for Item B');
INSERT INTO test_1 VALUES ('3', 'Item C', 'Description for Item C');
INSERT INTO test_1 VALUES ('4', 'Item D', 'Description for Item D');
INSERT INTO test_1 VALUES ('5', 'Item E', 'Description for Item E');


DROP TABLE IF EXISTS test_2;
CREATE TABLE test_2 (
  id int(11) NOT NULL AUTO_INCREMENT,
  ids varchar(32) NOT NULL,
  PRIMARY KEY (id)
);

-- ----------------------------
-- Records of test_2
-- ----------------------------
INSERT INTO test_2 VALUES ('1', '1,2,5');

我想返回(A)将给出的相同结果,但是来自(B)

(A) SELECT t1.*, t2.id as control FROM test_1 t1 LEFT JOIN test_2 t2 ON t1.id IN (1,2,5);
(B) SELECT t1.*, t2.id as control FROM test_1 t1 LEFT JOIN test_2 t2 ON t1.id IN (t2.ids) 

问题是MySQL IN需要一个数组,而我有一个来自t2.ids列的字符串。有什么出路吗?

1 个答案:

答案 0 :(得分:1)

感谢所有贡献的人。不过,我能够通过MySQL FIND_IN_SET

找到我的解决方案
SELECT t1.*, t2.id as control FROM test_1 t1 LEFT JOIN test_2 t2 ON t1.id= FIND_IN_SET(t1.id, t2.ids);