首页 > 解决方案 > 如果点与它相交,请指定位置名称 MySQL

问题描述

我正在使用 MySQL 8.0

我有两张桌子:location_table、rent_table

location_tables 看起来像:

location_name    polygon 
 A                BLOB
 B                BLOB 
 ...

多边形是 POLYGON 数据类型。

租表看起来像:

user_id    rent_time    rent_location   
   1           x           BLOB
   2           x           BLOB
  ...

其中rent_location 是 POINT 数据类型

对于rent_table 中的每一行,我想创建一个列来指示它属于哪个location_name。如果 user_id rent_location 与 location_name = A 新列相交,则 A

它看起来像这样:

user_id    rent_time    rent_location    location_name
   1           x           BLOB                A
   2           x           BLOB                B
  ...

提前致谢!

我试过的:

我可以通过使用来一一做

select *
     , st_intersects(A, Point(ST_X(work_location), ST_Y(work_location))) as location_A
     , st_intersects(B, Point(ST_X(work_location), ST_Y(work_location))) as location_B 
     , st_intersects(C, Point(ST_X(work_location), ST_Y(work_location))) as location_C
 from rent_table;

这在我事先设置 A、B、C 变量但我想直接从 location_table 获取位置多边形时有效。

我可以使用如下子查询:

select *
     , st_intersects((select polygon from location_table where location_name = 'A'), Point(ST_X(work_location), ST_Y(work_location))) as location_A
 from rent_table;

但是我在rent_table 中有数百万行,因此我不希望select 语句中的子查询为每一百万行运行。

标签: mysqlmysql-8.0

解决方案


你可以做:

select
  r.*, 
  l.location_name
from rent r
left join location l on ST_CONTAINS(l.polygon, r.rent_location)

推荐阅读