是否可以创建触发器将值复制到另一行(在同一个表中)的同一字段中?

时间:2013-07-22 15:38:10

标签: mysql triggers

我的下表test包含字段

id (PK), 
Project Code (CFK), 
item code (CFK) 
date_code
行可能看起来像:

id, project code, item code, date code
1,  project1,     item1,     1220 
2,  project1,     item2,     1224
3,  project1,     item1,     null
3,  project1,     item4,     null
4,  project1,     item1,     null

要更新日期代码,我可以使用简单的更新表

来完成
update table test
set date_code='1220' 
where project_code='project1' and item_code='item1'

但这可以通过插入和更新的触发器来完成吗?

我希望触发器在更新表语法中找到相同/匹配的复合外键字段(项目代码和项目代码),并在日期代码字段的其他行中复制相同的值?

在date_code字段被赋予值之前,所有行都将存在,因此它是最后完成的。

1 个答案:

答案 0 :(得分:3)

你在找这样的东西吗?

CREATE TRIGGER tg_projects_insert
BEFORE INSERT ON projects
FOR EACH ROW
  SET NEW.date_code = IF(NULLIF(TRIM(NEW.date_code), '') IS NULL,
  (
    SELECT date_code 
      FROM projects
     WHERE project_code = NEW.project_code 
       AND item_code = NEW.item_code
     LIMIT 1
  ), NEW.date_code);

CREATE TRIGGER tg_projects_update
BEFORE UPDATE ON projects
FOR EACH ROW
  SET NEW.date_code = IF(NULLIF(TRIM(NEW.date_code), '') IS NULL,
  (
    SELECT date_code 
      FROM projects
     WHERE project_code = NEW.project_code 
       AND item_code = NEW.item_code
     LIMIT 1
  ), NEW.date_code);

现在我们可以在项目表中插入和更新行

-- insert a new row and let the trigger to set date_code automatically
INSERT INTO projects VALUES (5, 'project1', 'item1', NULL);

-- update all rows that currently have NULL in date_code 
-- and let the trigger to set date_code automatically
UPDATE projects SET date_code = NULL WHERE date_code IS NULL;

-- insert a new row and explicitly set a value to date_code
INSERT INTO projects VALUES (6, 'project2', 'item1', '1115');

这是 SQLFiddle 演示