简体   繁体   中英

How to update a value in 1 table with the newly created PK of another table

I'm currently developing a project where I need to create a record in one table and leave the last column as NULL and update this later with the PK of another table (to establish a link).

Table 1 is a table for courses and table 2 is a table for the feedback form for each course.

The user first makes the course which is inserted in to table 1, THEN they make the feedback form which is inserted in to table 2.

Now I wanted to use a PK+FK relation here but, I can't set the FK of table 1 as the record hasn't yet been created in table 2.

For example, table 1 has the columns:

id(int)(PK), column1(int), column2(int), linkColumn(int)

Table 2 has the columns:

id(int)(PK), column1(int),...

I need to be able to make a record in table 1 and set linkColumn to NULL initially.

Then I need to create a record in table 2 and update linkColumn in table 1 with the Primary key of the newly created record in table 2.

How would I go about this?

Thanks!

Edit: I'm using PHP as the SQL handler

Use Triggers on insert for each row on Table2.

What Database are you using?

EDIT:

CREATE TRIGGER T_TABLE2_AI
AFTER INSERT
ON TABLE2 FOR EACH ROW

BEGIN

  update Table1 set linkColumn = :new.ID where column1 = :new.column1;

END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM