存储过程实现split功能并查询,可以进索引。
首先建一张表:cross_join_id
CREATE TABLE `cross_join_id` (
`id` int(11) DEFAULT NULL,
KEY `idx_id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
表里面是从1到你所要的最大循环数,最多不要超过5000,。如图:
存储过程核心代码如下:
(
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(n.accid,',',m.id),',',-1) AS accid
FROM cross_join_id AS m
CROSS JOIN (
SELECT in_newstype AS accid
) AS n
WHERE m.id>=1
AND m.id<(LENGTH(n.accid)-LENGTH(REPLACE(n.accid,',',''))+2)
)
in_newstype:输入的参数,默认是逗号分隔的字符串。
当in_newstype=1,2,3,4,5时
结果:
以下是两种应用:
SELECT varstdate AS stdate,vareddate AS eddate,b.accid,SUM(b.chgbonus) AS bonus
FROM (
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(n.accid,',',m.id),',',-1) AS accid
FROM cross_join_id AS m
CROSS JOIN (
SELECT in_accid AS accid
) AS n
WHERE m.id>=1
AND m.id<(LENGTH(n.accid)-LENGTH(REPLACE(n.accid,',',''))+2)
) AS a
INNER JOIN accountcharge AS b
ON a.accid=b.accid
WHERE b.chgdate>=varstarttime
AND b.chgdate<varcurtime
AND FIND_IN_SET(b.chgtype,in_chgtype)
GROUP BY b.accid;
SELECT id,optype,content,title,newstype,idx,pagenum,createuser,modifydate,starttime,endtime,sourcetype,isoneself,modifydate
FROM page_position_history
WHERE id=(CASE WHEN in_id='' THEN id ELSE in_id END)
AND createuser=(CASE WHEN in_user='' THEN createuser ELSE in_user END)
AND sourcetype=(CASE WHEN in_sourcetype='' THEN sourcetype ELSE in_sourcetype END)
AND SUBSTR(newstype,1,4) IN
(
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(n.accid,',',m.id),',',-1) AS accid
FROM cross_join_id AS m
CROSS JOIN (
SELECT in_newstype AS accid
) AS n
WHERE m.id>=1
AND m.id<(LENGTH(n.accid)-LENGTH(REPLACE(n.accid,',',''))+2)
)
ORDER BY modifydate DESC
LIMIT varidx,pagesize
) AS m;
条件限定:
一种是:给1,2,3,则查某属性是1或2或3的记录
一种是:给1015,2012,3000,则查记录某属性以1015或2012或3000开头的记录
在这感谢一下教我方法的李前辈,原先我是用网上创建虚拟表的方法实现功能的。