문제

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
도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top