如何从两个不同的 table 中获取两个不同的列并将其放入具有一对一映射的第三个 table 中?

How to fetch two different columns from two different tables and put it into a third table with one to one mapping?

假设我有两个 tables parent_table 和 parent_id 列以及 child_table 和 child_id 列。现在我必须在另一个名为 mapping_table 的 table 中为 child 和 parent 提供映射,其中 parent_id 和 child_id 作为列。我怎样才能在 postgresql 9.5 中做到这一点?两个 table 中的记录数都很大,所以我无法手动执行此操作。建议我做这个映射的最佳方法

假设table中的记录是这样的: parent_table:

|parent_id|
 1
 2
 3

child table:

|child_id|
 01
 02
 03

结果应该是这样的: 映射 table

parent_id | child_id
1         | 01
2         | 02
3         | 03

您可以使用如下查询:

INSERT INTO mapping_table (parent_id, child_id)
SELECT t1.parent_id, t2.child_id
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY parent_id) AS rn,
           parent_id
    FROM parent_table) AS t1
JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY child_id) AS rn,
           child_id
    FROM child_table) AS t2
ON t1.rn = t2.rn;

查询使用 ROW_NUMBER 以便将两个表相互关联。这导致 1-1 映射。

Demo here