请教Mysql触发器问题,插入A表,更新B表
版本:Mysql5.0
数据库:Test
表:voteItem(id,title,ticketNumber),主键:id,自增长整型。title:投票项标题。ticketNumber:获得投票数。
表:ticket(id,voteItemID,ip),主键:id,自增长整型。voteItemID:外键到表voteItem的主键。ip:进行投票的IP地址。
需求:在插入数据到ticket表的时候,插入数据项关联的外键项的'ticketNumber'值能自增。
也就是出现一张投票时,投票项的获得投票数自己能发现这个事件,并进行投票数自增。
不知道描述是否清楚,请大家帮忙。
[解决办法]
也就是ticketNumber+1?
TRIGGER:
UPDATE voteItem SET ticketNumber=ticketNumber+1 WHERE ID=NEW.voteItemID
[解决办法]
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.voteItemID; -> 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)
[解决办法]
不建议在TRIGGER中做统计,用连接即可得到,TRIGGER少用,会影响性能