我有一个MySQL查询,列出了餐馆、酒店等的结果。每一行都有纬度和经度数据。
我需要按照相对于用户搜索位置的距离对结果进行排序(页面加载后,我就有了相应的纬度和经度)。
我还有一个php函数,它以公里为单位返回两个lat/lng对之间的距离:
distance($lat1,$lng1,$lat2,$lng2);但是如何根据这个距离对查询结果进行排序呢?
现在,假设查询是简单的
mysql_query("select * from merchants");在其中插入order by distance(latitude,longitude,'$center_lat','$center_long')会给出一个错误,显示为FUNCTION dbname.distance does not exist。我曾经考虑过在页面加载后立即创建一个带有距离的临时MySQL表,然后按此进行排序,但这似乎有点过分了。是吗?
发布于 2012-05-17 17:26:25
你能创建一个和你的MySQL函数做同样事情的PHP函数吗?如果你能做到这一点,这将是最简单、最有效、通常也是最好的方式。如果你发布了你的distance()函数的源代码,我会看看如何将它转换成MySQL。
如果做不到这一点,您将不得不在PHP中执行排序,这在使用array_multisort()时是相对简单的(请看示例#3对数据库结果进行排序):
<?php
// Connect to database, yada yada yada
// Do the query
$query = "
SELECT *
FROM merchants
";
$result = mysql_query($query);
// Fetch the results into a 2 dimensional array.
// Also create an array with the results of the distance function
$rows = $sortcol = array();
while ($row = mysql_fetch_assoc($result)) {
$sortcol[] = $row['distance'] = distance($row['latitude'], $row['longitude'], $center_lat, $center_long);
$rows[] = $row;
}
// Sort the results
array_multisort($sortcol, SORT_ASC, $rows);
// Rows should now be sorted
print_r($rows);发布于 2012-05-17 17:18:27
您认为您的MySql服务器进程如何调用您的PHP进程来执行函数?
这是行不通的-- SQL在过去的50年里从来没有像这样工作过。
你提交一个字符串到SQL服务器,它必须是可计算的,而不是在你的主机中。显然,您的MySql不知道该函数。
https://stackoverflow.com/questions/10632832
复制相似问题