我有这种情况,需要将记录添加到两个具有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
是否有这样的查询,或者首选的方法是这样做?
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;