2016-06-26 83 views
0

我嘗試製作一個代碼,用於計算某個給定座標的最近位置。然而,我陷入了以下錯誤:根據座標之間的距離選擇位置

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

數據從pgadminIII數據庫檢索。所有幫助是值得歡迎

<?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; 

回答

1

having是當你組/彙總的東西,需要一個分組後的情況。你的情況,你需要使用where:用於聚合使用組時和數據集後應用

SELECT id, (...) AS distance 
FROM  parking 
WHERE distance < 150 
ORDER BY distance 
LIMIT 10 
+0

謝謝!但我仍然得到一個錯誤:語法錯誤或「附近」線5:從停車^在根線15(想法?) –

+0

糟糕,我把WHERE子句放在錯誤的地方。請交換FROM和WHERE子句。更新。 – trincot

+0

這是否回答了您的問題? – trincot

0
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發佈具有使用。所以一個where語句會更適合你的。第二個距離是列別名,所以它不會在where子句中可用,通過將整個計算放在where子句中可以解決這個問題。或者使用子選擇。

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; 
相關問題