Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update rows of two tables that have foreign key restrictions

Tags:

sql

postgresql

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 |
+-----+-----+------------+
like image 725
H35am Avatar asked Dec 20 '15 16:12

H35am


1 Answers

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

like image 164
a_horse_with_no_name Avatar answered Oct 22 '22 04:10

a_horse_with_no_name