Question

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
Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top