MySQL计算距离(简单解决方案)
我有下一个查询,用于获取给定距离和给定邮政编码内的地址。距离是根据经度和纬度数据计算的。
在此示例中,我已将用户输入替换为仅值(纬度= 52.64,长= 6.88,所需距离= 10公里)
查询:
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2) + POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses distance
WHERE distance < 10
ORDER BY `distance` DESC
给出未知列距离作为错误消息。 当省略 where 子句时,我得到了表的每条记录,包括它们的计算距离。在这种情况下,我必须获取整个表。
我如何才能只获取所需的记录?
预先感谢您的任何评论!
I have the next query for getting addresses within a given distance and given postal code. Distance is calculated, based upon longitude and latitude data.
In this example i have replaced the user-input for just values (lat=52.64, long=6.88 en desired distance=10km)
the query:
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2) + POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses distance
WHERE distance < 10
ORDER BY `distance` DESC
gives unknown column distance as error message.
when leaving out the where clausule i get every record of the table including their calculated distance. In this case i have to fetch the whole table.
How do i get only the desired records to fetch??
Thanks in advance for any comment!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能从 sql 语句的其他部分引用 select 子句中的别名。您需要将整个表达式放在 where 子句中:
更简洁的解决方案是使用子查询来生成计算数据:
演示:http://www.sqlize.com/q96p2mCwnJ
You can't reference an alias in the select clause from another part of the sql statement. You need to put the whole expression in your where clause:
A cleaner solution would be to use a sub-query to generate the calculated data:
Demo: http://www.sqlize.com/q96p2mCwnJ
正如 mellamokb 注释,您不能在 <代码>WHERE子句。 但是,您可以在
中执行此操作HAVING
子句:如果您有很多地址,您可能需要考虑通过尽早排除其中一些地址来优化查询。例如,使用合适的索引,以下版本可能会快得多:
As mellamokb notes, you can't reference column aliases in the
WHERE
clause. You can, however, do it in aHAVING
clause:Ps. If you have lots of addresses, you might want to consider optimizing the query by ruling out some of them early. For example, with suitable indexes, the following version might be considerably faster:
您将计算别名为“距离”,但您也将表“lp_relations_addresses”别名为“距离”。尝试给它们起一个不同的名称,如下所示:
You are aliasing the calculation as 'distance', but you are also aliasing table 'lp_relations_addresses' as 'distance'. Try giving them a different name like this: