且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更新具有外键限制的两个表的行

更新时间:2023-01-20 13:54:01

在 Postgres 中,您可以使用可写 CTE 在单个语句中更新两个表.

假设这个表设置:

create table a (rid integer主键,ride text,qunta integer);创建表b(孩子整数主键,删除整数引用a,日期日期);

CTE 将是:

with new_a as (更新一个摆脱 = 110其中rid = 1)更新 b摆脱 = 110其中rid = 1;

由于(不可延迟的)外键是在语句级别评估的,并且主键和外键都在同一个语句中更改,所以这是有效的.

SQLFiddle:http://sqlfiddle.com/#!15/db6d1/1

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