我知道可以自动增量值,但我想知道是否可以根据其他两个字段的值填充字段。我有一个包含字段的表:
CREATE TABLE pligg_links (
...
link_votes INT,
link_reports INT,
link_votes_total INT,
...
);
字段link_votes_total应保存从link_reports中减去的字段link_votes的值。所以基本上,这是数学等式:link_votes_total = link_votes - link_reports
。这是可能的,而不必在存储数据之前使用php来执行此操作吗?
答案 0 :(得分:3)
是的,可以通过为BEFORE INSERT
创建触发器,为BEFORE UPDATE
创建另一个触发器来完成此操作:
DELIMITER //
CREATE TRIGGER trig_mytable BEFORE INSERT ON my_table
FOR EACH ROW
BEGIN
SET NEW.link_votes_total = NEW.link_votes - NEW.link_reports;
END
//
CREATE TRIGGER trig_mytable BEFORE UPDATE ON my_table
FOR EACH ROW
BEGIN
SET NEW.link_votes_total = NEW.link_votes - NEW.link_reports;
END
//
DELIMITER ;
进一步阅读:
答案 1 :(得分:1)
请参阅:http://dev.mysql.com/doc/refman/5.1/en/triggers.html
DELIMITER //
CREATE TRIGGER bir_links
BEFORE INSERT ON links
FOR EACH ROW
BEGIN
SET link_votes_total = NEW.link_votes - NEW.link_reports;
END;
//
CREATE TRIGGER bur_links
BEFORE UPDATE ON links
FOR EACH ROW
BEGIN
SET link_votes_total = NEW.link_votes - NEW.link_reports;
END;
//
DELIMITER ;