[英]Joining two tables (from different databases) based on whether lat and long from one table are present in the polygon of the other
I'm trying to join two tables (in different databases: database_1 and database_2) based on whether the latitude and longitude (stored in one table) falls inside the defined polygons of the other table.我正在尝试根据纬度和经度(存储在一个表中)是否落在另一个表的定义多边形内来连接两个表(在不同的数据库中:database_1 和 database_2)。 Just for some context, my first table (containing lat and long in database_1) looks like:只是在某些情况下,我的第一个表(在 database_1 中包含 lat 和 long)看起来像:
Code price Latitude Longitude
0 A001 1200 43.65 -79.1
1 A3421 150 40.78 -73.9
2 B 300 42.82 -67.3
3 HCO 450 22.22 -22.2
4 WREA 200 39.80 32.3
And the other table (containing the polygon of type geometry defined by the column geometry) stored in database_2:另一个表(包含由列几何定义的几何类型的多边形)存储在database_2中:
tier_name tier2_name geometry
0 Sample 1 Sample 1 [GEOMETRY - 2.7 KiB]
1 Sample 2 Sample 2 [GEOMETRY - 2.7 KiB]
2 Sample 3 Sample 3 [GEOMETRY - 2.7 KiB]
3 Sample 4 Sample 4 [GEOMETRY - 2.7 KiB]
4 Sample 5 Sample 5 [GEOMETRY - 2.7 KiB]
... ... ... ...
I would ideally want my result to contain the appropriate tier_name and tier_name2 along with all the fields of the first table:理想情况下,我希望我的结果包含适当的 tier_name 和 tier_name2 以及第一个表的所有字段:
Code price Latitude Longitude tier_name tier2_name
0 A001 1200 43.65 -79.1 Sample 5 Sample 5 <-- The point (43.65 and -79.1) is in the polygon sample 5
1 A3421 150 40.78 -73.9 Sample 5 Sample 5
2 B 300 42.82 -67.3 <-- This point is in none of the polygons of dataframe #2
3 HCO 450 22.22 -22.2 Sample 2 Sample 2
4 WREA 200 39.80 32.3 Sample 3 Sample 3
... ... ... ... ... ... ....
My attempt at the solution (since I'm using python) was to do a join based on whether st_within as follows:我对解决方案的尝试(因为我使用的是 python)是根据 st_within 是否如下进行连接:
cnx = mysql.connector.connect(user='root', password='', unix_socket='/data/mysql/mysql.sock', database='database_2')
test=pd.read_sql("""SELECT tier_name, tier2_name, st_astext(geometry),
FROM `table_2`
JOIN `database_1`.`table_1` as Table1
ON ST_WITHIN(Point([Table1.Latitude,
Table1.Longitude], 4326), `table_2`.geometry)
""", cnx)
However, the error I keep getting is:但是,我不断收到的错误是:
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[database_1].[Table_1] Table_1
ON ST_WITHIN(geometry::P' at line 5
For MariaDB you should be using backticks to quote identifiers (not necessary).对于 MariaDB 您应该使用反引号来引用标识符(不是必需的)。 This query should work assuming the databases are both on the same MariaDB instance假设数据库都在同一个 MariaDB 实例上,该查询应该可以工作
SELECT
`t1`.`Code`,
`t1`.`price`,
`t1`.`Latitude`,
`t1`.`Longitude`,
`t2`.`tier_name`,
`t2`.`tier2_name`
FROM `database_2`.`table_2` t2
JOIN `database_1`.`Table_1` t1
ON ST_WITHIN(Point(`t1`.`Latitude`, `t1`.`Longitude`), `t2`.`geometry`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.