mysql 存储逗号分割存储好吗,使用mysql变量保存逗号分隔的值,以用于where in子句...

I have to run a query like this (query 1) -

select something from sometable where someId in (1,2,3)

I would like to keep a variable for the IDs part, like this (query 2) -

set @myIds = "1,2,3";

select something from sometable where someId in (@myIds);

But this does not give the expected result (gives an empty result set), and no query error as well.

I checked that if I wrap the comma separated IDs inside quotes, the query results an empty result set (query 3) -

select something from sometable where someId in ("1,2,3");

I guess when I am using variable @myIds like I showed above (query 2), it is evaluating to the above query (query 3).

解决方案

You need to have a dynamic sql on this,

SET @myIds = '1,2,3';

SET @sql = CONCAT('select something from sometable where someId in (',@myIds,')');

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值