基于距离的查询建议


Distance based query advice

好吧,自从 iv 不得不做这种复杂的事情以来已经有一段时间了,我有点困惑。

我有一个库类,它接收邮政编码并在输入的邮政编码半径内返回一个邮政编码的关联数组,邮政编码作为键,与原始邮政编码的距离作为值。

示例:FK27DJ => 0.094146570284875

Web 应用程序是一个外卖餐厅查找器,我需要运行一个查询,该查询将找到每种类型中最接近输入邮政编码的外卖。

根据takeaway_type_id字段,有 4 种类型的外卖。因此,如果用户输入自己的邮政编码,则将向他们显示每种类型的单个外卖,这也是该类型中最接近输入的邮政编码的外卖。

因此,我需要从库类中传入邮政编码数组,并在外卖表中搜索每种类型中最接近的外卖。

这有意义吗?

外卖表包含以下相关字段:

ID(整数(, takeaway_type_id(整数(, 邮政编码

这可以在单个查询中完成吗?该网站是基于php的。

是的。由于这看起来像英国邮政编码,因此您需要另一个将邮政编码映射到 GPS 坐标(经度和纬度(的表。你可以从这里得到它。http://jamiethompson.co.uk/web/2008/07/24/full-uk-postcode-database-for-free/(其他地方也可能有,http://www.freepostcodes.org.uk/退房(

然后你需要在SQL中做一个"选择",连接两个表,计算你可以在SQL中做的距离。"SQRT(POWER(Long1 - long2,2( + POWER(Lat1 - Lat2,2(("将为您提供大致距离。警告:由于需要为每一行计算此值,因此请将可能的结果限制为长+范围,纬度+范围。

为了获得准确的距离,您确实需要一些三角。这是我在最近的应用程序中使用的一个函数,它做类似的事情,你应该能够调整它来工作,甚至构建 int othe SQL 查询。

function CalculateDistance($Longitude1, $Latitude1, $Longitude2, $Latitude2) {
    // Not perfect for curvature of earth on the diaganol, but it's close enough ;)
    $LatDiff = abs($Latitude1 - $Latitude2);
    $LongDiff = abs($Longitude1 - $Longitude2);
    // Convert to meters - 1 deg latitude = 111.12km
    $mLatDiff = $LatDiff * 0.11112;
    $mLongDiff = $LongDiff * 0.11112 * cos(($Latitude1 + $Latitude2) / 2);
    // Work out difference.
    $Diff = sqrt( ($mLatDiff * $mLatDiff) + ($mLongDiff * $mLongDiff) );
    return $Diff;
}

编辑:添加代码示例

未经测试的代码,但从最近的项目中编辑。需要语法检查和调整,但会给出这个想法。

$UserPostcode = "AB1 2FG";
// Find the Long/Lat of the user (you don;t have to do this, but it saves a lot of DB stress)
// Postcodes is the table that links users to postcodes
$sql = 'SELECT long, lat FROM postcodes WHERE postcode="' . mysql_real_escape_string($UserPostcode) .'"';
// ... Missing a few lines of check row exists, error reporting etc
$UserLat = $row['lat'];
$UserLong = $row['long'];
// Next, come up with an acceptable range so as not to over-stress the DB:
// What are the acceptable limits?
// 1 deg latitude = 111.12km
// LATITUDE: 1km = 1/111.2 degrees of latitude = 0.0089992800575953923686105111591073
// LONGITUDE: 1km = 1/(111.2 * cos(LATITUDE))
$RangeLat = 8 * 1/111.2; // For 8km = 5 miles. Work out what you want here, the larger = more DB stress
$RangeLong = 8 * 1/(111.2 * cos(deg2rad($UserLat)); // For 8km = 5 miles. Work out what you want here, the larger = more DB stress
// Now the query you want.
// You'll need to change this to get restauants by group, but this gives you the essence of what you need:
$sql = 'SELECT r.restaurant_id, r.OtherDetails, r.postcode,
                  p.lat, p.long,
                  SQRT(POWER(p.lat-'.$UserLat.',2) + POWER(p.long-'.$UserLong.',2)) AS distance 
           FROM resturants r
             LEFT JOIN postcodes p ON r.postcode=p.postcode
           WHERE p.lat >='.($UserLat - $RangeLat).' AND p.lat <='.($UserLat + $RangeLat).' AND p.long>='.($UserLong-$RangeLong).' AND p.long>='.($UserLong+$RangeLong).'
           ORDER BY SQRT(POWER(p.lat-'.$UserLat.',2) + POWER(p.long-'.$UserLong.',2)) ASC';
if (!$result = mysql_query($sql)) { ExitError(4, $sql . '<br />' . mysql_error()); }
while ($row = mysql_fetch_assoc($result)) {
        // This is where you can count the 4 in each category, and disregard if you get more that 4.
        // If you get less than 4, offer to expand the range - or stick in a loop and do it automatically.
        // Also for efficienty, I'd suggest you remove the "distance" calculation from the SQL and use the function above
        // The function above it more accurate as it users cosine. Then simply sort by distance here instead on in SQL.
        // Also note the above function is written for the northern hemisphere. Also won't work across the date line ;)
        // But that shouldn't be a worry.
}
mysql_free_result($result);

但是 - 可以在一个查询中完成吗:当然,如果你想关闭SQL服务器

同样,没有经过测试,但会给你该怎么做的要点。不过,我强烈建议不要这样做!

$sql = 'SELECT r.restaurant_id, r.OtherDetails, r.postcode,
                  p.lat, p.long,
                  SQRT(POWER(p.lat-p2.lat,2) + POWER(p.long-p2.long,2)) AS distance 
           FROM resturants r
             LEFT JOIN postcodes p ON r.postcode=p.postcode
             LEFT JOIN postcodes p2 ON p2.postcode="' . mysql_real_escape_string($UserPostcode) .'"
           ORDER BY SQRT(POWER(p.lat-p2.lat,2) + POWER(p.long-p2.long,2)) ASC';

如果你走这条路,并且你想要超高精度,我会让你研究如何让 COS 进入那里:)。你需要的 mySQL 函数是 RADIANS(( 和 COS((