简体   繁体   English

如何将插入查询和更新查询与不同的表合并到单个查询中?

[英]How to combine insert query and update query with different tables into single query?

How to combine this query into single query? 如何将此查询合并为单个查询?

INSERT INTO transactions (quantity) VALUES (2);
UPDATE items SET stock = 5 WHERE id = 1;

thank you. 谢谢。

Simple answer? 简单的答案? You can't. 你不能 There is no SQL command that allows you to insert into one table and simultaneously update another table. 没有SQL命令允许您插入一个表并同时更新另一个表。

You can, however, make them part of the same transaction so that they both happen, or both don't happen, so you don't end up in a situation where the INSERT succeeded but the UPDATE failed 但是,您可以使它们成为同一事务的一部分,以使它们都发生或不发生,因此,您不会最终遇到INSERT成功但UPDATE失败的情况

You can update two tables at the same time but updating one and inserting other table in one query is not possible. 您可以同时更新两个表,但是无法在一个查询中更新一个表并插入另一个表。 But the loop hole would the use of procedures with start transaction like @Caius Jard mentioned. 但是漏洞会使用带有启动事务的过程,例如@Caius Jard。

In Postgres, you can use an updatable CTE: 在Postgres中,您可以使用可更新的CTE:

with i as (
    INSERT INTO transactions (quantity)
        VALUES (2)
        RETURNING *
    )
UPDATE items
SET stock = 5
WHERE id = 1;

The returning clause would actually let you use values from the insert in the update . returning子句实际上将允许您使用update insert值。 This construct is a big convenience in Postgres. 在Postgres中,此构造非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM