在触发器中引用其他表的列?

时间:2019-06-11 19:37:44

标签: sqlite

给出:

CREATE TABLE worktags (
        worktag_id      integer         not null primary key,
        worktag         character(32)   not null default '' unique,

            ...
        last_updated    character(32)   not null default '[Error]'
);
CREATE TABLE truefacts (
        about           character(32)   not null primary key,
        fact            character(32)   not null
);

以下内容:

CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
  UPDATE worktags SET
    last_updated = truefacts.fact WHERE truefacts.about = 'Last Worktag Update';
END;

给出错误:

  

错误:第52行附近:没有这样的列:truefacts.fact

但是该列存在,并且syntax diagram似乎表明

  

[[schema-name . ] table-name . ] column-name

expr右侧的合法SET column-name = expr

1 个答案:

答案 0 :(得分:1)

您将需要使用子查询来访问其他(truefacts)表(因为在任何地方都没有 FROM truefacts),例如:-

CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
  UPDATE worktags SET
    last_updated = (SELECT fact FROM truefacts WHERE about = 'Last Worktag Update');
END;

说,那么就不需要触发器,因为子查询可以嵌入到UPDATE中。

例如考虑以下示例:-

DROP TRIGGER IF EXISTS zz_worktags_last_updated;
DROP TABLE IF EXISTS worktags;
DROP TABLE IF EXISTS truefacts;
CREATE TABLE worktags (
        worktag_id      integer         not null primary key,
        worktag         character(32)   not null default '' unique,
        last_updated    character(32)   not null default '[Error]'
);
CREATE TABLE truefacts (
        about           character(32)   not null primary key,
        fact            character(32)   not null
);

INSERT INTO truefacts VALUES('Last Worktag Update','xxx');
INSERT INTO worktags (worktag,last_updated) VALUES('mytag',(datetime('now')));
SELECT * FROM worktags;
UPDATE worktags SET last_updated = (SELECT fact FROM truefacts WHERE about = 'Last Worktag Update'), worktag = 'aaaa' WHERE worktag_id = 1;
SELECT * FROM worktags;

UPDATE truefacts SET fact = 'zzzz' WHERE rowid = 1;
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
    last_updated = (SELECT truefacts.fact FROM truefacts WHERE truefacts.about = 'Last Worktag Update');
END;

UPDATE worktags SET worktag = 'bbbb' WHERE worktag_id = 1;
SELECT * FROM worktags;

此:-

  1. 删除表并触发它们(如果存在)(以便可以重新运行)
  2. 创建2个表并填充它们。
  3. 从工作标签表(仅1行)中选择所有内容

  4. 使用子查询来更新工作标签表中的行(这是无需触发的示例)

  5. 已更新(无触发器)工作表中选择所有内容。
  6. 更新truefact的事实列(以显示触发器有效) 6.创建触发器。
  7. 更新工作标签表中的行,更改工作标签列,将更改留给last_updated列由触发器完成。
  8. 由触发器更新的工作标签表中选择所有内容。

运行上述结果将导致:-

enter image description here

enter image description here

最后

enter image description here