【问题标题】:How can I return a column from select query of INSERT....SELECT....RETURNING如何从 INSERT....SELECT....RETURNING 的选择查询中返回一列
【发布时间】:2018-04-23 07:34:40
【问题描述】:

我认为stock_details 为:

item INTEGER,
quantity NUMERIC(8,2),
discount NUMERIC(8,2),
taxable NUMERIC(8,2),
tax NUMERIC(8,2),
unique_serial CHARACTER VARYING(50)
.....

我还有两张表:

invoice_item(
    id SERIAL PRIMARY KEY,
    item INTEGER,
    quantity NUMERIC(8,2),
    discount NUMERIC(8,2),
    taxable NUMERIC(8,2),
    tax NUMERIC(8,2),
) 

unique_invoice_item(
    invoice_item INTEGER PRIMARY KEY,
    unique_serial CHARACTER VARYING(50),
    item INTEGER,
    ..............,
    UNIQUE(unique_serial),
    UNIQUE(unique_serial, item),
    FOREIGN KEY (invoice_item) REFERENCES invoice_item(id)
}

我希望将来自stock_details 的选择查询中的数据插入invoice_itemunique_invoice_item。我尝试使用以下查询来执行此操作:

WITH t AS (
    INSERT INTO invoice_item AS ii (item, quantity, discount, taxable, tax) 
    SELECT s.item, s.quantity, s.discount, s.taxable, s.tax
    FROM stock_details AS s WHERE ..........
    RETURNING ii.id, s.unique_serial
)
INSERT INTO unique_invoice_item 
SELECT t.id, s.unique_serial, ........
FROM t JOIN stock_details AS s ON t.unique_serial = s.unique_serial

但上述查询不正确,因为它无法返回 CTE 中的 s.unique_serial。

现在我的问题:

有什么方法可以返回 CTE 中的 s.unique_serial 列?

还有其他方法可以实现吗?

注意 除了idinvoice_itemunique_serialunique_serial, item 组合在unique_invoice_item 表中,invoice_item 表中没有任何独特的列。 invoice_item 中的item 列和表unique_invoice_item 中的item 列都引用了一个通用的外部表。

【问题讨论】:

    标签: postgresql common-table-expression


    【解决方案1】:

    我认为,根据我的经验,你不能直接得到s.unique_serial。我建议你如下两种方式:

    1. 在表invoice_item中添加列unique_serial并插入它的值,你可以在Returning得到它的值
    2. 编写一个函数,对stock_details 查询中的每条记录进行循环。因此,您拥有所需的所有数据。

    希望我的回答对你有所帮助。

    【讨论】:

      【解决方案2】:

      不确定,但从另一篇文章看来你可以使用类似的东西

      WITH x AS (
      SELECT s.item, s.quantity, s.discount, s.taxable, s.tax, s.unique_serial
      FROM stock_details AS s WHERE ..........),
      t AS (
          INSERT INTO invoice_item AS ii (item, quantity, discount, taxable, tax) 
          values(x.item, x.quantity, x.discount, x.taxable, x.tax)
          RETURNING ii.id, s.unique_serial
      )
      INSERT INTO unique_invoice_item 
      SELECT t.id, s.unique_serial, ........
      FROM t JOIN stock_details AS s ON x.unique_serial = s.unique_serial
      

      参考 - https://dba.stackexchange.com/questions/50693/can-the-returning-clause-return-source-columns-that-are-not-inserted

      【讨论】:

      • 您建议的查询不正确。在 CTE t 中,您没有选择 x。所以它不会起作用。您提供的链接给出了交叉连接的示例。即,如果我的 CTE t 返回 10 个 id 并且唯一序列号为 10,则表 unique_invoice_item 的结果将是 10*1000 行,导致插入时出错。
      猜你喜欢
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多