I have a situation with two tables where one has a foreign key pointing to the other table (simplified) schema:
CREATE TABLE table1 (
name VARCHAR(64) NOT NULL,
PRIMARY KEY(name)
);
CREATE TABLE table2 (
id SERIAL PRIMARY KEY,
table1_name VARCHAR(64) NOT NULL REFERENCES table1(name)
);
Now I regret using the name
column as primary key in table1
- and would like to add integer serial key instead. Since I already have data in the database I guess I need to do this carefully. My current plan is as follows:
- Drop the foreign key constraint:
table2(name)
withALTER TABLE table2 DROP CONSTRAINT table2_table1_name_fkey;
- Drop the primary key constraint on
table1(name)
withALTER TABLE table1 DROP CONSTRAINT name_pkey;
. - Add a unique constraint on
table1(name)
withALTER TABLE table1 ADD UNIQUE(name);
- Add a automatic primary key to
table1
withALTER TABLE table1 ADD COLUMN ID SERIAL PRIMARY KEY;
. - Add a new column
table1_id
totable2
withALTER TABLE table2 ADD COLUMN table1_id INT;
- Update all rows in
table2
- so that the new column (which will be promoted to a foreign key) gets the correct value - as inferred by the previous (still present) foreign keytable1_name
.
I have completed steps up to an including step 5, but the UPDATE
(with JOIN
?) required to complete 6 is beyond my SQL paygrade. My current (google based ...) attempt looks like:
UPDATE
table2
SET
table2.table1_id = t1.id
FROM
table1 t1
LEFT JOIN table2 t2
ON t2.table1_name = t1.name;
CodePudding user response:
You do not need JOIN
in UPDATE
.
UPDATE
table2 t2
SET
table1_id = t1.id
FROM
table1 t1
WHERE
t2.table1_name = t1.name;