mysql in变量值的处理方案

2022年12月31日09:29:24

Mysql数据库中,在一个范围存查询数据时候,有时候我们会用到in

例如:

SELECT contract_code FROM ContractInfo 
WHERE contract_code IN ('ht123456','ht654321');

很显然,这个查询没有任何问题,可以正确执行。

那么,如果将'ht123456','ht654321'作为变量传递给mysql,mysql是否还能执行呢?

SET @nu = "'ht123456','ht654321'";
select contract_code from ContractInfo 
WHERE contract_code IN (@nu);

经验证,查询不到任何结果!why?

直接上代码

SET @nu = "'ht123456','ht654321'";
EXPLAIN 
select contract_code from ContractInfo 
WHERE contract_code IN (@nu);
SHOW WARNINGS;

可以看到,mysql优化器并没有想预期的那样,将'ht123456','ht654321'作为变量传递@nu。

原因:mysql认为,set设置的变量是一个字符串,并不是一个集合,而in后面应该跟随一个集合,所有返回为0,在某些版本的mysql中,会将where后面直接解析为0,即:where 0,查询并没有成功;

如何解决这个问题?

方案一:采用预处理方式

SET @nu = "'ht123456','ht654321'";
set @sql = CONCAT("SELECT contract_code FROM ContractInfo WHERE contract_code IN (",@nu,");");
prepare exesql from @sql;  
execute exesql;
deallocate prepare exesql;

其中:

prepare是定义预处理语句;execute为执行预处理语句;deallocate释放定义。

方案二:mysql函数

1、FIND_IN_SET:返回字符串在以逗号分隔的原始字符串中首次出现的位置。

SET @nu = "ht123456,ht654321";
SELECT contract_code FROM ContractInfo WHERE FIND_IN_SET (contract_code ,@nu)> 0;

2、POSITION:返回字符串在原始字符串中首次出现的位置。

SET @nu = "ht123456,ht654321";
SELECT contract_code FROM ContractInfo WHERE POSITION(contract_code in @nu)> 0;

3、INSTR:将字符串str从第x位置开始,y个字符长的字符串替换为字符串instr。

SET @nu = "ht123456,ht654321";
SELECT contract_code FROM ContractInfo WHERE INSTR(@nu,contract_code )>0;

  • 作者:firesea
  • 原文链接:https://blog.csdn.net/firesea/article/details/118569770
    更新时间:2022年12月31日09:29:24 ,共 1235 字。