我如何以1-1关系(单个事务)将数据存储到表中

问题描述 投票:0回答:1

我有这种情况,需要将记录添加到两个具有1-1关系的表中。 (例如:table1和table2)在single transaction中。

我首先需要将项目添加到table1并获取刚刚添加的项目的id。现在,我需要使用table1.id创建第二个项目table_one_id,它是table2中具有该ID的外键。

这只是为了确保如果第二个表失败,我在表1中没有数据!

imagine table1 = users and table2 = cars

如果没有users.id,我不想在数据库中存储cars.userId

是否有这样的查询,或者首选的方法是这样做?

sql postgresql backend
1个回答
0
投票
CREATE TABLE t1 (id PRIMARY KEY, attributes);
CREATE TABLE t2 (id UNIQUE, FK (id) REFERENCES t1 (id), attributes);
START TRANSACTION;
INSERT INTO t1 (attributes) 
    VALUES ('t1 attribute values');
INSERT INTO t2 (id, attributes) 
    SELECT id, 't2 attribute values' 
    FROM t1 
    WHERE attributes = 't1 attribute values';
COMMIT;
© www.soinside.com 2019 - 2024. All rights reserved.