传入list/分隔符/表名/字段名 创建list的临时表用来关联,优化in慢查询解决方案
CREATE DEFINER=``@`` PROCEDURE `proc_splitStrList`(
in strLst VARCHAR(3000),
in splitTag varchar(1),
in outTableName VARCHAR(200),
in outFieldName varchar(100)
)
BEGIN
select case when Trim(splitTag)='' then ',' else Trim(splitTag) end into @splitTag;
select case when Trim(outTableName)='' then 'Temp_ItemList' else Trim(outTableName) end into @outTableName;
select case when Trim(outFieldName)='' then 'item' else Trim(outFieldName) end into @outFieldName;
set @strLst=strLst;
drop TEMPORARY table if EXISTS tmp_Rt;
create TEMPORARY table tmp_Rt
(
id int,
item varchar(500)
) ENGINE=MEMORY;
insert DELAYED into tmp_Rt
SELECT
(@rownum := @rownum + 1) AS id,
SUBSTRING_INDEX(SUBSTRING_INDEX(@strLst,@splitTag,help_topic_id+1),@splitTag,-1) AS item
FROM
mysql.help_topic,
(SELECT
@rownum := 0) AS rn
WHERE
help_topic_id < LENGTH(@strLst)-LENGTH(REPLACE(@strLst,@splitTag,''))+1;
set @cSQL='drop TEMPORARY table if EXISTS ';
select CONCAT(@cSQL,@outTableName,'; \n') into @cSQL;
prepare stmt from @cSQL; -- 预处理需要执行的动态SQL,其中stmt是一个变量
EXECUTE stmt; -- 执行SQL语句
deallocate prepare stmt; -- 释放掉预处理段
select CONCAT('create TEMPORARY table ',@outTableName,'(id int,`',@outFieldName,'` varchar(500) ) ENGINE=MEMORY;') into @cSQL;
prepare stmt from @cSQL; -- 预处理需要执行的动态SQL,其中stmt是一个变量
EXECUTE stmt; -- 执行SQL语句
deallocate prepare stmt; -- 释放掉预处理段
select CONCAT('insert into ',@outTableName,'\n select id,item from tmp_Rt;') into @cSQL;
prepare stmt from @cSQL; -- 预处理需要执行的动态SQL,其中stmt是一个变量
EXECUTE stmt; -- 执行SQL语句
deallocate prepare stmt; -- 释放掉预处理段
end
当程序中写到最后需要in的时候,可能效率较低,可以把in中的内容拆分写入临时表进行关联操作。