如何在MySQL中查询用逗号分隔的字符串值?

时间:2018-08-03 09:55:03

标签: mysql

结果1来自表1:

select types from table1 where id = 123456;

结果:

934046, 934049

然后,将结果1作为table2的参数:

select GROUP_CONCAT(name) from table2 where id in (
    select types from table1 where id = 123456
);

但是结果1是一个字符串值, 这样的结果:

NULL

事实上我想得到这个:

select GROUP_CONCAT(name) from table2 where id in ('934046', '934049');
or
select GROUP_CONCAT(name) from table2 where id in (934046,934049);

但它可能仍然像这样:

select GROUP_CONCAT(name) from table2 where id in ('934046,934049');

1.
select REPLACE(types,',','\',\'') types from table1 where id=123456

1.1 
result:  934046',' 934049

1.2 
select GROUP_CONCAT(name) from table2 where ids in ( 
select REPLACE(types,',','\',\'') types from table1 where id=123456
); 

2.
select CONCAT('\'',REPLACE(types ,',','\',\''),'\'') from table1 where 
id=123456

2.1 
reuslt: '934046',' 934049' 

2.2 
select GROUP_CONCAT(name) from table2 where ids in ( 
select CONCAT('\'',REPLACE(types ,',','\',\''),'\'') from table1 where 
id=123456); 

该字符串值不能作为参数,我该怎么做才能以正确的方式获取ID?

2 个答案:

答案 0 :(得分:0)

$query = "select types from table1 where id = 123456"; 

$result = mysql_query($query) or die(mysql_error());

$array = array();

while($row = mysql_fetch_array($result))
{
   $array[] = $row['types'];
}

$array = implode(",",$array);

$query2 = "select GROUP_CONCAT(name) from table2 where id in ($array)";

我用其他查询创建了代码。

答案 1 :(得分:0)

select GROUP_CONCAT(t.name) from table2 t
where exists(
    select 1 from table1
    where id = 123456
    and LOCATE(concat(', ', t.id, ',') , concat(', ', types, ',') )>0
)