用MySQL创建触发器

时间:2015-01-04 00:37:05

标签: php mysql triggers phpmyadmin

两个表:用户和消息

 CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(10) NOT NULL,
`password` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`verifystring` varchar(20) NOT NULL,
`active` tinyint(4) NOT NULL,
`usertype` tinyint(4) NOT NULL,
`img` varchar(200) DEFAULT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

 CREATE TABLE IF NOT EXISTS `messages` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`topic_id` int(11) NOT NULL,
`subject` varchar(100) NOT NULL,
`body` text NOT NULL,
`img` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`),
 KEY `topic_id` (`topic_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;

触发:

CREATE TRIGGER `updateimg` AFTER UPDATE ON `users`
 FOR EACH ROW begin
    update messages set img = new.img where messages.user_id = users.id;
end

img字段是保留用户已上传的图像的名称。 如何在更新时将表格用户的值img复制到表格消息中?

1 个答案:

答案 0 :(得分:0)

多数民众赞成应该这样做:

CREATE TRIGGER update AFTER UPDATE ON table1
    for each ROW
    begin
        update table2 set y = new.y where table2.user_id = new.id;
    end