[英]How to get values from another table and insert the result into another query
I am trying to to build a basic sql query where I have a table of petrol stations and another table of POI in my sql database and I would like to get all petrol stations within a radius of a POI 我正在尝试建立一个基本的SQL查询,其中在我的sql数据库中有一个加油站表和另一个POI表,我想在POI半径内获得所有加油站
I have the following query: 我有以下查询:
SELECT *, ( 6371000 * acos( cos( radians(15.4383252) )
* cos( radians( petrol_stations.lat ) ) * cos( radians( petrol_stations.lng ) - radians(47.0450591) )
+ sin( radians(15.4383252) ) * sin(radians(petrol_stations.lat)) ) )
AS distance FROM petrol_stations HAVING distance < 500
and it seems to work fine, however I have to hard-code the coordinates of the POI into the query. 似乎工作正常,但是我必须将POI的坐标硬编码到查询中。 Is it possible to adapt the query such that the POI coordinates are pulled from the other table if provided with the name such as
main square
? 是否可以修改查询,以使POI坐标从另一个表中拉出(如果提供了名称,例如
main square
?
Thanks in advance. 提前致谢。
assuming you have a georef poi table as 假设您有一个georef poi表为
table_poi
id name lat lng
1 my_poi 47.0450591 15.4383252
you could try a cross join for related all your petrol_stations with all your POI 您可以尝试交叉联接所有与您的POI相关的所有petrol_stations
SELECT *
, ( 6371000 * acos( cos( radians(table_poi.lng) )
* cos( radians( petrol_stations.lat ) ) * cos( radians( petrol_stations.lng )
- radians(table_poi.lat) )
+ sin( radians(table_poi.lng) ) * sin(radians(petrol_stations.lat)) ) )
AS distance
FROM petrol_stations
CROSS JOIN table_poi
HAVING distance < 500
or using where (as requested by MarlinPierce) 或在哪里使用(根据MarlinPierce的要求)
SELECT *
, ( 6371000 * acos( cos( radians(table_poi.lng) )
* cos( radians( petrol_stations.lat ) ) * cos( radians( petrol_stations.lng )
- radians(table_poi.lat) )
+ sin( radians(table_poi.lng) ) * sin(radians(petrol_stations.lat)) ) )
AS distance
FROM petrol_stations
CROSS JOIN table_poi
WHERE ( 6371000 * acos( cos( radians(table_poi.lng) )
* cos( radians( petrol_stations.lat ) ) * cos( radians( petrol_stations.lng )
- radians(table_poi.lat) )
+ sin( radians(table_poi.lng) ) * sin(radians(petrol_stations.lat)) ) ) < 500
and if you want filter for a POI name 以及是否要过滤POI名称
SELECT *
, ( 6371000 * acos( cos( radians(table_poi.lng) )
* cos( radians( petrol_stations.lat ) ) * cos( radians( petrol_stations.lng )
- radians(table_poi.lat) )
+ sin( radians(table_poi.lng) ) * sin(radians(petrol_stations.lat)) ) )
AS distance
FROM petrol_stations
WHERE table_poi.name like '%your_poi_name%'
CROSS JOIN table_poi
HAVING distance < 500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.