postgresql:如何将数据从两个单独的表导入到同一表的同一行?

时间:2019-12-09 20:33:42

标签: sql postgresql relational-database

我正在使用postgresql从bytearray(b'\x00\x02\x00\x02\x00\x04\x00\x03\x00\x01') 创建countries表。 single_sales_records看起来像这样:

single_sales_records

在此之前,我创建了一个sales_id |region |country| <Many other columns!> --------------------------------------------------------------------------- 1 |Australia and Oceania |Tuvalu | ... 2 |Central America and the Caribbean|Grenada| ... 3 |Europe |Russia | ... . . 表,基本上是这样的:

regions

我要创建的region_id | region ------------------------------- 1 |asia 2 |australia and oceania 3 |central america and the caribbean 4 |north america 5 |sub-saharan africa 6 |middle east and north africa 7 |europe 表(一个地区可以有很多国家)应该看起来像这样:

countries

我有一个查询可以帮助我填充“地区”表:

country_id | country | region_id
-----------------------------------------
1          |korea    |1
.
.
.

我在当前查询中遇到麻烦,该查询应该由“国家”表填充:

INSERT INTO regions (region)
SELECT DISTINCT region
FROM single_sales_records;

执行此操作时,我的“国家/地区”表与区域内的国家/地区不匹配-而是列出了所有国家/地区,然后为该区域添加了7行。看起来像这样:

INSERT INTO countries (country)
SELECT DISTINCT country
FROM single_sales_records;
INSERT INTO countries (region_id)
SELECT DISTINCT region_id
FROM regions;

有人可以帮我将国家与相关地区相匹配吗?

我试图寻找其他文章,但是他们谈论的是将数据插入两个单独的表中,或者谈论联接(我不认为这确实需要联接...对吗?)。

非常感谢! [本文经过编辑以包含single_sales_records]

1 个答案:

答案 0 :(得分:0)

您想将JOIN的表一起INSERT

INSERT INTO countries (region_id, country)
    SELECT DISTINCT r.region_id, country
    FROM single_sales_records ssr JOIN
         regions r
         ON ssr.region = r.region;