mysql触发器关联表更新
mysql> create table voteItem -> ( -> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -> title varchar(30), -> ticketNumber int -> ); Query OK, 0 rows affected (0.09 sec) mysql> mysql> create table ticket( -> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -> voteItemID INT references voteItem(id) , -> ip varchar(30) -> ); Query OK, 0 rows affected (0.09 sec) mysql> mysql> insert into voteItem values (null,'aaaaa',0); Query OK, 1 row affected (0.03 sec) mysql> mysql> select * from voteItem; +----+-------+--------------+ | id | title | ticketNumber | +----+-------+--------------+ | 1 | aaaaa | 0 | +----+-------+--------------+ 1 row in set (0.00 sec) mysql> mysql> DELIMITER | mysql> mysql> CREATE TRIGGER testref AFTER INSERT ON ticket -> FOR EACH ROW BEGIN -> update voteItem set ticketNumber=ticketNumber+1 where id = new.v oteItemID; -> END; -> | Query OK, 0 rows affected (0.09 sec) mysql> mysql> DELIMITER ; mysql> mysql> insert into ticket values (null,1,'127.0.0.1'); Query OK, 1 row affected (0.08 sec) mysql> select * from ticket; +----+------------+-----------+ | id | voteItemID | ip | +----+------------+-----------+ | 1 | 1 | 127.0.0.1 | +----+------------+-----------+ 1 row in set (0.00 sec) mysql> select * from voteItem; +----+-------+--------------+ | id | title | ticketNumber | +----+-------+--------------+ | 1 | aaaaa | 1 | +----+-------+--------------+ 1 row in set (0.00 sec)
摘自csdn论坛(http://bbs.csdn.net/topics/300203458)。