postgresql - 使用一个 cte postgres 进行多次插入
问题描述
我是postgres的初学者。在做一个虚拟项目时,我遇到了这个问题。
我有两张表,可以说 t1 和 t2。t1 与 t2 有 1->Many 关系。
我正在尝试编写一个 SQL 语句,它首先在 t1 中插入数据,然后使用 t1 中的 id 在 t2 中插入多行。
像这样的东西。
WITH ins AS (
INSERT INTO t1(t1_col)
VALUES (4)
RETURNING t1_id
)
INSERT INTO t2(t1_id, t2_col) VALUES (ins.t1_id, 3), (ins.t1_id, 4)...
t1 结构 -> (t1_id primary_key 序列,t1_col 整数)。
t2 结构 -> (t2_id primary_key 序列,t1_id 整数,t2_col 整数)。
这样做的正确方法是什么。
先感谢您。
解决方案
除了插入 withVALUES
子句,您可以插入SELECT
. 一般来说,它将是:
WITH ins AS (
INSERT INTO table1(target columns)
VALUES (some values) -- or -- SELECT something FROM somewhere
RETURNING some_id
)
INSERT INTO table2(target columns)
SELECT ins.some_id, other columns or expressions
FROM ins;
多行的变体(固定列表)
WITH ins AS (
INSERT INTO table1(target columns)
VALUES (some values) -- or -- SELECT something FROM somewhere
RETURNING some_id
)
INSERT INTO table2(target columns)
SELECT ins.some_id, UNNEST(ARRAY[3,4,...])
FROM ins;
其中 3,4.... 是值列表
推荐阅读
- javascript - totalVowels 变量未更新
- scala - 使用 Map 重命名和选择 Apache Spark Dataframe (Scala) 上的列
- artifactory - 我可以为 npm 注册表使用通用存储库类型吗?
- apache-spark - 使用 Spark.sql 插入 TempView
- typo3 - 在 TYPO3 8.7 中通过“插入记录”插入时显示 tt_address 记录
- ironpython - Spotfire-IronPython:设置 FilePath 属性
- r - 在 ggplot2 中绘制多个密度:如何添加具有不同比例的额外变量?
- sql - Oracle Sql 将短日期转换为字符串或长日期
- variables - 带有变量 dir 的 gradle fileTree
- c# - _ = WriteItems(channel.Writer, count, delay);中的下划线是什么意思