如何使用触发器分割数据并将其传输到另一个表

时间:2016-04-22 14:27:17

标签: mysql triggers mysql-workbench

我想创建触发器,如果​​向表中添加新行 IDVU **它会将列<**> UV 分开of string ,示例(Jo Black),分为两个字符串(单词) Jo Black 插入表 sep V (适用于Jo) U (黑色)

CREATE TRIGGER `edit` AFTER INSERT 
ON `idvu` 
FOR EACH ROW BEGIN

    IF new.VU = '% %' THEN
        SET @V = 'K' ,@U = 'P';
    else
        SET @V = 'NEW',@U = 'NEW';
    END IF;

    INSERT INTO sep (ID2,V, U) VALUES (new.ID,@V, @U);

END$$

最终结果应如下所示:

来自Table sep

Table UDIV

问题是我不知道在使用触发器时是否需要拆分字符串?

*请原谅我的第四天使用MySQL写剧本技巧! :) *

1 个答案:

答案 0 :(得分:0)

只需添加substring_index()

即可轻松实现
create table IDVU (
`ID` int not null ,
`VU` varchar(45),
PRIMARY KEY (`id`),
KEY `ix_VU` (`VU`)
)ENGINE = InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Insert into idvu values (1,'Jo Black');

drop table sep;
create table sep select 
    idvu.id as ID2 ,
    SUBSTRING_INDEX(SUBSTRING_INDEX(VU, ' ', 1), ' ', -1) as V,
    SUBSTRING_INDEX(SUBSTRING_INDEX(VU, ' ', 2), ' ', -1) as U
        from IDVU;
Alter table sep add ID1 mediumint(8) unsigned NOT NULL primary key AUTO_INCREMENT first;
alter table sep add KEY `ix_ID2` (`ID2`)  ;
alter table sep add CONSTRAINT `C1` FOREIGN KEY (`ID2`) REFERENCES `IDVU`(`ID`) ON DELETE CASCADE ON UPDATE CASCADE;

delimiter $$
drop trigger `edit` $$
CREATE TRIGGER `edit` AFTER INSERT 
ON `idvu` 
FOR EACH ROW BEGIN

    IF new.VU like '% %' THEN
        SET @V = SUBSTRING_INDEX(SUBSTRING_INDEX(new.Vu, ' ', 1), ' ', -1) ,
            @U = SUBSTRING_INDEX(SUBSTRING_INDEX(new.Vu, ' ', 2), ' ', -1);
    else
        SET @V = 'NEW',@U = 'NEW';
    END IF;

    INSERT INTO sep (ID2,V, U) VALUES (new.ID,@V, @U);

END$$

delimiter ;