我想创建触发器,如果向表中添加新行 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$$
最终结果应如下所示:
来自 的
问题是我不知道在使用触发器时是否需要拆分字符串?
*请原谅我的第四天使用MySQL写剧本技巧! :) *
答案 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 ;