POSTGRESQL:在同一个查询中插入 2 个表,使用从第一个插入生成的 ID 在第二个插入中

POSTGRESQL: Insert into 2 tables in the same query, using ID generated from first insert in the second insert

表格

CREATE TABLE "assets"
(
    "uuid" uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    "symbol" text NOT NULL,
    "name" text NOT NULL,
    "decimal" numeric DEFAULT 18,
    "img_small" text DEFAULT '',
    "img_large" text DEFAULT '',
    "gecko_id" text
)

CREATE TABLE "chain_asset"
(
    "uuid" uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    "chain_uuid" uuid NOT NULL,
    "asset_uuid" uuid NOT NULL,
    "contract" text NOT NULL,
    "chain_contract" text NOT NULL,    
)

我的查询

    `WITH x AS (
    INSERT INTO assets (symbol, name, decimal) VALUES (, , ) RETURNING uuid
     )
    INSERT INTO chain_asset (chain_uuid, asset_uuid, contract, chain_contract) VALUES (, x.uuid ,, )
`,

我正在使用 pg promise。我想使用相同的查询插入 2 tables。我需要插入资产 table 的 uuid,以便插入 chain_asset table。使用 x.uuid 无效,出现以下错误

Error: missing FROM-clause entry for table "x"

您不需要 VALUES(),只需要 SELECT select-clause 中的文字:


WITH x AS (
    INSERT INTO assets(symbol,name,decimal) VALUES (, , )
    RETURNING uuid
    )
INSERT INTO chain_asset(chain_uuid,asset_uuid,contract,chain_contract)
SELECT ,x.uuid,,
FROM x
;