I have the below query where I join two tables, the query is working when I remove the group by at the end, but it returns too many rows for me.
The first priority is to have the order by distance (which is calculated within the query), subsequently I want only the unique tr_id with the smallest distance.
When I use group by I get the following error:
1064 – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
GROUP BY tr_id LIMIT 0, 30at line 2.
SELECT op.operatorid AS tr_id, de.latitude AS
tolatitude, de.longitude AS tolongitude, de.surname AS tosurname,
de.firstname AS tofirstname, de.did AS to_id,
de.tzz AS tmzz,
op.bkk AS tobkk,
( 3959 * acos( cos( radians(52.524368165134284) ) * cos( radians(
de.latitude )
) * cos( radians( de.longitude) - radians(13.410530090332031) ) + sin(
radians(52.524368165134284) ) * sin( radians( de.latitude ) ) ) )
AS distance
FROM de
INNER JOIN op ON de.did = op.did
WHERE de.type='Dutch' AND de.longitude > 11.6118868785
AND de.longitude < 15.2091733022 AND de.latitude > 50.7257249533
AND de.latitude < 54.323011377 having distance < 200
GROUP BY tr_id
ORDER BY distance
HAVING clause must come after any GROUP BY clause,so your query must be:-