0

我有以下查询,我在其中加入两个表,当我最后删除 group by 时查询正在工作,但它为我返回了太多行。

第一要务是拥有order by距离(在查询中计算),随后我只想要距离最小的唯一tr_id

当我使用时,group by我收到以下错误:

1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以GROUP BY tr_id LIMIT 0, 30在第 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
4

2 回答 2

4

ORDER BY应在之后指定 GROUP BY

PS:我在你的 中没有看到聚合函数的使用SELECT,所以整个查询看起来有点混乱

于 2012-05-06T11:00:19.280 回答
4

HAVING 子句必须在任何 GROUP BY 子句之后,因此您的查询必须是:-

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  
GROUP BY tr_id having distance < 200
ORDER BY distance
于 2012-05-06T11:22:39.323 回答