I have a table with gps locations of restaurants chains and would like to return the addresses of the restaurants closest to point (A) within a certain radius
SELECT *
, MIN(distance($lat, $lon, lat, lon)) as mile开发者_如何学运维s
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
returns error
misuse of aggregate: MIN()
I think that your problem is that you only are grouping by restaurant_id
. When you use an aggregation function as MIN, MAX, SUM, AVG
, etc, you need to include every column in the SELECT
statement that are not in any aggregation function. In this case you have two options, either in the SELECT
you only put restaurant_id
as the following:
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
Or you put every other column included in the '*' on the grouping (because you can't use GROUP BY *
).
I bet that you're calling a function which is distance($lat, $lon, lat, lon)
, don't you?
Have you tried using a simple subtraction between $lat
and lat
and have it return the minimum value using the MIN
function?
MIN
's purpose is for use with a table field or some basic operation such as a subtraction, I guess. This might be the cause of the encountered error.
Up and foremost, avoid using *
while using aggregation functions, list the columns you require in your query.
Perhaps providing us with sample data might help us find a way around to work you through.
Lamak was somewhat right but this is what i ended up doing instead
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
hope this helps somebody else
精彩评论