首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MySQL中查询逗号分隔的字符串值?

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

Stack Overflow用户
提问于 2018-08-03 17:55:03
回答 2查看 42关注 0票数 0

结果1来自table1:

代码语言:javascript
复制
select types from table1 where id = 123456;

结果:

代码语言:javascript
复制
934046, 934049

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

代码语言:javascript
复制
select GROUP_CONCAT(name) from table2 where id in (
    select types from table1 where id = 123456
);

但是,结果1是一个字符串值,所以结果:

代码语言:javascript
复制
NULL

事实上,我想要的是:

代码语言:javascript
复制
select GROUP_CONCAT(name) from table2 where id in ('934046', '934049');
or
select GROUP_CONCAT(name) from table2 where id in (934046,934049);

但它可能仍然是这样的:

代码语言:javascript
复制
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); 

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-03 18:49:33

代码语言:javascript
复制
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将如下所示:

代码语言:javascript
复制
    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

票数 0
EN

Stack Overflow用户

发布于 2018-08-03 18:06:25

代码语言:javascript
复制
$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)";

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51670023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档