【问题标题】:postgresql: how to import data from two separate tables into a single table into the SAME row?postgresql:如何将两个单独的表中的数据导入到单个表中的同一行中?
【发布时间】:2019-12-10 05:20:57
【问题描述】:

我正在使用 postgresql 从single_sales_records 创建countries 表。 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 表(1 个地区可以有多个国家/地区)应该如下所示:

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

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

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

我当前的查询有问题,该查询应该由“国家”表填充:

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

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

country_id | country | region_id
-----------------------------------------
1          |korea    |null
.
.
76         |haiti    |null
77         |null     |1
.
.
83         |null     |7

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

我试图寻找其他这样的文章,但他们正在谈论将数据插入到两个单独的表中,或者谈论连接(我认为这并不完全需要连接......对吗?)。

非常感谢! [这篇文章被编辑以包含 single_sales_records]

【问题讨论】:

  • 旁注:删除countries 中的region 列。您已经在 regions 中获得了该信息,并且可以从那里获取。
  • @stickybit 谢谢你的建议。您能否向我解释一下如果没有region,我会怎么做?我目前没有解决这个问题。谢谢!
  • 我不确定你现在想知道什么?如何离开列?从CREATE TABLE 语句中删除它。以后怎么取名字?在区域 ID 上加入区域表或使用相关子查询。
  • @stickybit 我想知道如何将regionscountries 表中的数据插入到一个新表中,该表中的国家与地区相关联。从您和@Gordon Linoff 的回复来看,我似乎需要使用 join,但 Gordon Linoff 的解决方案不起作用。因此,如果我能得到一个可行的解决方案,我将不胜感激(无论我是否在我的新表中包含region):)
  • single_sales_records 长什么样子? Edit 问题并包含它的示例。

标签: sql postgresql relational-database


【解决方案1】:

你想把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;

【讨论】:

  • @NathanBell 。 . .请设置一个 dbfiddle,以便我可以看到您正在使用的代码。
猜你喜欢
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
相关资源
最近更新 更多