简体   繁体   English

根据坐标之间的距离选择位置

[英]Selection of locations based on distance between coordinates

I attempt to make a code which calculates the nearest locations for a certain given coordinate. 我试图编写一个代码,以计算给定坐标的最近位置。 However I got stuck on the following error: 但是我陷入了以下错误:

ERROR: column "distance" does not exist  
LINE 5: `HAVING distance < 150`  
in ROOT\frontend3.php on line 16. 

Data is retrieved from pgadminIII database. 从pgadminIII数据库中检索数据。 All help is welcome 欢迎所有帮助

<?php 

include 'connection.php';

$lat = $_GET['lat'];
$lng = $_GET['lng'];

#Select inormation from Parking database
$result = pg_query($conn, "
SELECT id, ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) *     cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) 
AS distance 
FROM parking
HAVING distance < 150 
ORDER BY distance 
LIMIT 10
");
echo $result;

having is for when you group/aggregate stuff and need a condition after that grouping. having用于当您对物料进行分组/汇总并且在分组之后需要条件时。 In your case you need to use where : 你的情况,你需要使用where

SELECT   id, ( ... ) AS distance 
FROM     parking
WHERE    distance < 150 
ORDER BY distance 
LIMIT    10
SELECT
    id
    ,( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) *     cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance 
FROM parking
WHERE
    ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) *     cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) < 150
ORDER BY distance 
LIMIT 10;

2 issues HAVING is used when using group by for aggregations and is applied after the dataset. 2个问题HAVING在将group by用于聚合时使用,并在数据集之后应用。 So a where statement would be more appropriate for your. 因此,where语句更适合您。 Second distance is a column alias so it won't be available in a where clause you can solve that by putting the entire calculation in the where clause. 第二距离是列别名,因此在where子句中将不可用,您可以通过将整个计算放在where子句中来解决该问题。 Or use a sub select. 或使用子选择。

SELECT *
FROM (
    SELECT
       id
       ,( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) *     cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance 
    FROM parking
) t
WHERE
    distance < 150
ORDER BY distance 
LIMIT 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM