You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何按ID匹配从另一表插入数据并生成指定结果?

How to Update and Insert Data to Achieve Your Desired Table A Result

Hey there! Let's work through this PostgreSQL issue step by step. First, let's unpack why your original query threw that error: when using INSERT ... SELECT, you can't directly reference the target table (a) in the WHERE clause like that—PostgreSQL doesn't know how to link a and b unless you explicitly include a in the query's FROM clause (and even then, that's not what you need here). Also, your original insert only specified the gender column, but you need to include id too to match rows correctly.

To get the exact result you want (each ID in Table A has two rows with the Gender value from Table B), you'll need two simple steps: update the existing rows in Table A, then insert the rows from Table B into Table A. Here's how to do it:

Step 1: Update Existing Rows in Table A

First, overwrite the original Gender values in Table A to match the corresponding IDs in Table B:

UPDATE a
SET gender = b.gender
FROM b
WHERE a.id = b.id;

This will change Table A's initial Gender values (1, 2, 3) to F, M, F respectively.

Step 2: Insert Rows from Table B into Table A

Next, add duplicate entries by inserting all rows from Table B into Table A:

INSERT INTO a (id, gender)
SELECT id, gender FROM b;

This will add three new rows to Table A, mirroring the ID and Gender pairs from Table B.

Optional: Run in a Transaction

To ensure both operations succeed or fail together (so you don't end up with partial updates), wrap them in a transaction:

BEGIN;
-- Update existing rows
UPDATE a
SET gender = b.gender
FROM b
WHERE a.id = b.id;

-- Insert new rows
INSERT INTO a (id, gender)
SELECT id, gender FROM b;
COMMIT;

After running these commands, Table A will look exactly like your desired output:

IDGender
1F
1F
2M
2M
3F
3F

内容的提问来源于stack exchange,提问作者user8396969

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:16:59