I have two tables: one is foreign reference table lets say table a and other one is the data table lets say table b. Now, when I need to change the data in table b, but I get restricted by table a. How can I change "rid" in both tables without getting this message?
"ERROR: insert or update on table "table a" violates foreign key constraint "fk_boo_kid" SQL state: 23503
Detail: Key (kid)=(110) is not present in table "table b".
Example query to update both tables:
UPDATE table b table a SET rid = 110 WHERE rid =1
table b +-----+-------+-------+ | rid | ride | qunta | +-----+-------+-------+ | 1 | car | 1 | | 2 | bike | 1 | +-----+-------+-------+ table a +-----+-----+------------+ | kid | rid | date | +-----+-----+------------+ | 1 | 1 | 20-12-2015 | | 2 | 2 | 20-12-2015 | +-----+-----+------------+
In Postgres you can use a writeable CTE to update both tables in a single statement.
Assuming this table setup:
create table a (rid integer primary key, ride text, qunta integer);
create table b (kid integer primary key, rid integer references a, date date);
The CTE would be:
with new_a as (
update a
set rid = 110
where rid = 1
)
update b
set rid = 110
where rid = 1;
As (non-deferrable) foreign keys are evaluated on statement level and both the primary and foreign key are changed in the same statement, this works.
SQLFiddle: http://sqlfiddle.com/#!15/db6d1/1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With