mysql中如何查询逗号分隔的字符串值?

k2fxgqgv  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(329)

结果1来自表1:

select types from table1 where id = 123456;

结果:

934046, 934049

然后,结果1作为表2的参数:

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?

f4t66c6m

f4t66c6m1#

$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)";

我用不同的查询创建了代码。

f0ofjuux

f0ofjuux2#

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
)

sql将如下所示:

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

使用函数concat()让t.id和类型具有相同的格式,然后使用locate()查找类型中是否存在t.id

相关问题