【问题标题】:How do I store data to tables in a 1-1 relationship (Single transaction)如何以 1-1 关系将数据存储到表中(单事务)
【发布时间】:2020-08-06 13:51:20
【问题描述】:

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

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

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

imagine table1 = users and table2 = cars

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

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

【问题讨论】:

  • 1:1 关系不存在。 1:仅(0 或 1)。
  • @Akina 当然存在,tech-recipes.com/rx/56738/…
  • 您使用的是 MySQL 还是 Postgresql?哪个环境?
  • @jarlh 我正在使用 PostgreSQL
  • @jarlh 但我只需要原始 sql 中的查询然后我可以为 postgreSQL 修改它

标签: sql postgresql foreign-keys sql-insert auto-increment


【解决方案1】:

您甚至可以在单个语句

中做到这一点
with new_parent as (
  insert into parent_table (<columns>)
  values (..)
  returning id; --<< this is the generated ID from parent_table
)
insert into child_table (parent_id, <other columns>)
select id, 42, 'some_value'
from new_parent;

另一种选择是使用lastval()

insert into parent_table (<columns>)
values (..);
insert into child_table (parent_id, <other columns>)
values (lastval(), ...);

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多