【问题标题】:SQL INSERT data from 2 tables来自 2 个表的 SQL INSERT 数据
【发布时间】:2021-10-16 14:58:03
【问题描述】:

我有 2 张桌子,postcodelatlngbranch

postcodelatlng

postcode lat lng
AB10 1XG 57.1441650 -2.1148480
AB10 6RN 57.1378800 -2.1214870
AB10 7JB 57.1242740 -2.1271900
AB10 5QN 57.1427010 -2.0932950
AB10 6UL 57.1375470 -2.1122330

branch

branch postcode
1 ZE2 9TL
4 BB1 7DJ
9 YO8 9DW

我正在尝试为branch 中的每个邮政编码创建一个新表,它会列出postcodelatlng 中的每个邮政编码。

New table

from to from_lat from_lng to_lat to_lng
ZE2 9TL AB10 1XG 60.4481370 -1.1943700 57.1441650 2.1148480
ZE2 9TL AB10 6RN 60.4481370 -1.1943700 57.1378800 -2.1214870
ZE2 9TL AB10 7JB 60.4481370 -1.1943700 57.1242740 -2.1271900
ZE2 9TL AB10 5QN 60.4481370 -1.1943700 57.1427010 -2.0932950
ZE2 9TL AB10 6UL 60.4481370 -1.1943700 57.1375470 -2.1122330
BB1 7DJ AB10 1XG 53.7490640 -2.4843190 57.1441650 2.1148480
BB1 7DJ AB10 6RN 53.7490640 -2.4843190 57.1378800 -2.1214870
BB1 7DJ AB10 7JB 53.7490640 -2.4843190 57.1242740 -2.1271900
BB1 7DJ AB10 5QN 53.7490640 -2.4843190 57.1427010 -2.0932950
BB1 7DJ AB10 6UL 53.7490640 -2.4843190 57.1375470 -2.1122330
YO8 9DW AB10 1XG 53.7743390 -1.0714240 57.1441650 2.1148480
YO8 9DW AB10 6RN 53.7743390 -1.0714240 57.1378800 -2.1214870
YO8 9DW AB10 7JB 53.7743390 -1.0714240 57.1242740 -2.1271900
YO8 9DW AB10 5QN 53.7743390 -1.0714240 57.1427010 -2.0932950
YO8 9DW AB10 6UL 53.7743390 -1.0714240 57.1375470 -2.1122330

我尝试在 Python 中使用 Pandas 和 SQLAlchemy 执行此操作,但我无法理解这一点,因此我认为仅在 SQL 中执行此操作可能更容易,但我也坚持这样做!

lat/lng 数据仅保存在 postcodelatlng 中,但这可以手动添加到 branch 表中(那里只有 42 个唯一的邮政编码(一些分支机构共享一个邮政编码))

branch 有 120 条记录,postcodelatlng 有 42 个唯一邮政编码和 1778786 条记录。

【问题讨论】:

  • “我正在尝试为分支中的每个邮政编码创建一个新表,它列出了 postcodelatlng 中的每个邮政编码。” CROSS JOIN?
  • 你从哪里得到值 from_lat, from_lng?
  • @MeysamaAsadi:from_latfrom_lng 将来自postcodelatlng 表中from 邮政编码的latlng 列。
  • 那么 to_lat 和 to_lng?
  • 目前也只存储在 postcodelatlng 表中,但如上所述,只有 42 个唯一值,因此如果需要,我可以先将它们添加到分支表中。谢谢

标签: python sql sql-server pandas sqlalchemy


【解决方案1】:

通过无条件连接,达到了所需的表,但我不知道 from_lat 和 from_lng 的值

insert into newtable
select b.postcode,p.postcode,"from_lat = ?","from_lng = ?",p.lat,p.lng
from branch b join postcodelatlng p on 1 = 1

或交叉连接

insert into newtable
select b.postcode,p.postcode,"from_lat = ?","from_lng = ?",p.lat,p.lng
from branch b cross join postcodelatlng p

【讨论】:

  • 这非常有效。我用SELECT DISTICNT postcode INTO postcode_temp FROM branch 创建了一个新的临时表,然后将 lat/lng 数据加入到该表中,首先将所有分支邮政编码数据隔离并加入到 lat/lng。然后使用交叉连接插入到新的最终表中。非常感谢您的帮助 Meysam
猜你喜欢
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多