表table1 结构如下id  name
当插入数据后把刚插入的数据做如下替换比如把字符串中的 aaa到bbb的所有字符替换为空
如提交的数据是 “测试数据aaa广告开始,广告结束bbb”希望最终插入name列的数据是"测试数据"

解决方案 »

  1.   

    mysql> create table table1 (id int primary key,col varchar(100));
    Query OK, 0 rows affected (0.23 sec)mysql> delimiter |
    mysql>
    mysql> CREATE TRIGGER testref BEFORE INSERT ON table1
        ->   FOR EACH ROW BEGIN
        ->          declare i ,j int;
        ->          set i=instr(new.col,'aaa');
        ->          set j=instr(new.col,'bbb');
        ->          if i>0 and j>i then
        ->                  set new.col=concat(left(new.col,i-1),substring(new.col,j+3));
        ->          end if;
        ->   END;
        -> |
    Query OK, 0 rows affected (0.19 sec)mysql>
    mysql> delimiter ;
    mysql>
    mysql> insert into table1 values (1,'aasdfaewrwrew');
    Query OK, 1 row affected (0.45 sec)mysql> select * from table1;
    +----+---------------+
    | id | col           |
    +----+---------------+
    |  1 | aasdfaewrwrew |
    +----+---------------+
    1 row in set (0.09 sec)mysql> insert into table1 values (2,'测试数据aaa广告开始,广告结束bbb');
    Query OK, 1 row affected (0.06 sec)mysql> select * from table1;
    +----+---------------+
    | id | col           |
    +----+---------------+
    |  1 | aasdfaewrwrew |
    |  2 | 测试数据      |
    +----+---------------+
    2 rows in set (0.00 sec)mysql>
      

  2.   


    update table1 set name=concat(substring_index(name,'aaa',1),substring_index(name,'bbb',-1));