Domanda

I have two tables, A & B:

TABLE A
id   |   name

TABLE B
id    |  name | fk_idA

I want to create trigger AFTER INSERT in TABLE B which updates fk_idA appropriate with the newest id from table A.

An example:

 TABLE A
id   |   name
 1   |   Andrew
 2   |   David

 TABLE B
id    |  name  | fk_idA
 1    | Photo1 |   2
È stato utile?

Soluzione

If the ID column is autoincrementing, the latest is the largest one, i.e., the one returned by MAX:

CREATE TRIGGER DefaultAIsLatest
AFTER INSERT ON TableB
FOR EACH ROW
WHEN NEW.fk_idA IS NULL
BEGIN
    UPDATE TableB
    SET fk_idA = (SELECT MAX(id)
                  FROM TableA)
    WHERE id = NEW.id;
END;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top