2010-11-30 102 views
0

的最小函數值我有一個表與餐館連鎖店的GPS位置,並想返回最近的餐館的地址,以點(A)一定半徑SQLite的選擇分組結果

SELECT * 
    , MIN(distance($lat, $lon, lat, lon)) as miles 
FROM all_restaurants 
WHERE lat between $lat1 and $lat2 
    AND lon between $lon1 and $lon2 
    AND miles < $miles 
GROUP BY restaurant_id 
ORDER BY miles ASC 
    , company_name ASC 
LIMIT 500 

回報誤差範圍內

誤用骨料的:)MIN(

回答

0

Lamak有點權,但是這是我落得這樣做,而不是

SELECT *, distance('+lat+','+lon+', lat, lon) as minmiles 
FROM all_restaurants 
WHERE restaurant_id || minmiles IN 
( 
    SELECT restaurant_id || MIN(miles) as fewmiles 
    FROM ( 
     SELECT restaurant_id, distance('+lat+','+lon+', lat, lon) as miles 
     FROM restaurant_master_combined 
     WHERE lat BETWEEN $lat AND $lat2 AND lon BETWEEN $lon1 AND $lon2 AND miles < $miles 
    ) 
    GROUP BY restaurant_id 
) 
ORDER BY ROUND(minmiles) ASC, company_name ASC 

希望這可以幫助別人

0

我敢打賭,你調用的函數,而distance($lat, $lon, lat, lon),不是嗎?

您是否嘗試過使用$latlat之間的簡單減法,並使用MIN函數返回最小值?

MIN的目的是用於表字段或一些基本操作,如減法,我想。這可能是遇到錯誤的原因。

最重要的是,避免在使用聚合函數時使用*,列出查詢中所需的列。

也許向我們提供樣本數據可能會幫助我們找到解決問題的方法。

1

我認爲你的問題是你只是按restaurant_id分組。當您使用聚合函數MIN, MAX, SUM, AVG等時,您需要在SELECT語句中包含任何不在任何聚合函數中的列。在這種情況下,你有兩個選擇,要麼在SELECT你只把restaurant_id如下所示:

SELECT restaurant_id 
     , MIN(distance($lat, $lon, lat, lon)) as miles 
    FROM all_restaurants 
    WHERE lat between $lat1 and $lat2 
     AND lon between $lon1 and $lon2 
     AND miles < $miles 
    GROUP BY restaurant_id 
    ORDER BY miles ASC 
     , company_name ASC 
    LIMIT 500 

或者你把包括每隔一列中的「*」的分組(因爲你不能使用GROUP BY * )。