为什么“group by”不能用于MySQL查询?

时间:2012-05-06 10:58:24

标签: mysql group-by

我有以下查询,我连接两个表,当我最后删除组时查询正在工作,但它为我返回太多行。

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

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

  

1064 - 您的SQL语法出错;查看与MySQL服务器版本对应的手册,以便在第2行GROUP BY tr_id LIMIT 0, 30附近使用正确的语法。

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

2 个答案:

答案 0 :(得分:4)

ORDER BY应在 GROUP BY

后指定

PS:我在SELECT中看不到聚合函数的使用情况,因此整个查询看起来有点混乱

答案 1 :(得分: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