mysql利用存储过程实现类似split的效果

问题前景:
       数据库存在关键字以“;”隔开,查询的结果集按关键字幅出现的次数降序排列,并按单个关键词在页面展示。以下为存储过程
CREATE PROCEDURE `proc_split`(
    inputstring varchar(1000),
    delim char(1)
)
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
begin
    declare strlen int;
    declare last_index int;
    declare cur_index int;
    declare cur_char VARCHAR(200);
    declare len int;
    set cur_index=1;
    set last_index=0;
    set strlen=length(inputstring);
    drop temporary table if exists splittable;/**/
    create TEMPORARY table splittable(
        id int AUTO_INCREMENT,
        value VARCHAR(20),
        PRIMARY KEY (`ID`),
        UNIQUE KEY `ID` (`ID`)
    ) ;
    WHILE(cur_index<=strlen) DO   
    begin
        if substring(inputstring from cur_index for 1)=delim or cur_index=strlen then
            set len=cur_index-last_index-1;
            if cur_index=strlen then
               set len=len+1;
            end if;
            insert into splittable(`value`)values(substring(inputstring from (last_index+1) for len));
            set last_index=cur_index;
        end if;
        set cur_index=cur_index+1;
    END;
    end while;
end 
/*测试*/
call proc_split('a;b;c;d',';');
select * from splittable;

上面只适合于对单个词做处理,可能我们自己遇到的情况是,将所有的字段(每个字段可能只包含一个关键词,也可能包含多个关键词)处理成一个多关键词处理,附带一个sql可以实现
select group_concat(name separator ';') as tags from tags where LENGTH(name)>0

参数说明:LENGTH(name)>0 是为空的字段不做处理

猜你喜欢

转载自hbsession.iteye.com/blog/1849339