[英]How to query a string value separated by comma in MySQL?
结果 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?
$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)";
我用不同的查询创建了代码。
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和types具有相同的格式,然后使用LOCATE()查找types中是否存在t.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.