Python 如何基于另一列插入列值
假设我有一个如下的postgresql表:Python 如何基于另一列插入列值,python,sql,database,pandas,postgresql,Python,Sql,Database,Pandas,Postgresql,假设我有一个如下的postgresql表: CustomerID | Pincode 还有一张这样的桌子 Pincode | City 我想在第一个名为City的表中创建一个新列,它映射第二个表中的City并插入它 最终结果 CustomerID | Pincode | City 请注意,第二个表包含唯一的pincode到城市映射,而第一个表可以有许多具有不同客户id的pincode(客户id是唯一的) 怎么做 如果不能在数据库中完成,那么我也可以使用python解决方案。让我们将这些表称
CustomerID | Pincode
还有一张这样的桌子
Pincode | City
我想在第一个名为City的表中创建一个新列,它映射第二个表中的City并插入它
最终结果
CustomerID | Pincode | City
请注意,第二个表包含唯一的pincode到城市映射,而第一个表可以有许多具有不同客户id的pincode(客户id是唯一的)
怎么做
如果不能在数据库中完成,那么我也可以使用python解决方案。让我们将这些表称为A和B。SQL查询:
SELECT A.CustomerID, A.Pincode, B.City
FROM A, B
WHERE A.Pincode = B.Pincode;
如果A中的数据为:
11
2.2
3.1
5.2
B:
11
2.2
结果将是:
11
2 2
3.1.1
5 2请在数据库中查找外键。假设每个PIN码都是唯一的,那么这里可能甚至不需要两个表,在这种情况下,您的问题与Python无关,而是使用您的基础SQL数据库。最好进行适当的
连接,而不是从进行多个。请编辑您的答案,为OP提供一些关于您这样做的内容和原因的上下文。
alter table first_table add column City text;
insert into first_table (CustomerID, Pincode, City)
select ft.CustomerID, at.Pincode, at.City
from first_table as ft
join another_table as at on ft.Pincode = at.Pincode
;