慢sql选择。两张桌子

时间:2013-09-10 18:08:02

标签: php mysql sql

在90210英里内搜索zipcodes时,我的脚本运行速度太慢。即使在zipcode数据库中也没有重复,它也会复制一些,因此DISTINCT u.id.除了只选择我需要的列,还有关于如何提高速度的想法?

<?php
$zipcode = queryDB("SELECT * FROM zipcodes WHERE zipcode='$location' LIMIT 1", 'a');

$distance = 30;
$sql = "SELECT DISTINCT zipcode, ( 3959 * acos( cos( radians(".$zipcode['lat'].") ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(".$zipcode['lon'].") ) + sin( radians(".$zipcode['lat'].") ) * sin( radians( lat ) ) ) ) AS distance FROM zipcodes HAVING distance <= $distance ORDER BY distance";
$zipcodes = queryDB($sql, 'r');

$sql = '';
while($row = mysqli_fetch_assoc($zipcodes)){
    $sql .= "u.category='$category' AND u.zipcode='".$row['zipcode']."' AND u.zipcode = l.zipcode";
    if($_GET['photos'] == 'y'){ $sql .= " AND photo_1!=''"; }
    $sql .= " OR ";
}
$sql = rtrim($sql, ' OR ');

$profiles = queryDB("SELECT DISTINCT u.id, u.*, l.city, l.state, l.zipcode FROM user_accounts as u, zipcodes as l WHERE $sql ORDER BY date_added DESC", 'r');
while($row = mysqli_fetch_assoc($profiles)){
//this is where i display the profile information
} ?>

更新:最大的问题是我的user_accounts选择没有使用连接。这是我更新的SQL查询。

    $sql = '';
$zipcodes = new ZipCodesRange($location, $distance);
foreach ($zipcodes->zipCodes as $zipcode){
    $sql .= "(u.category='$category' AND u.zipcode='".$zipcode['ZIPCODE']."'";
    if($_GET['photos'] == 'y'){ $sql .= " AND photo_1!=''"; }
    $sql .= ") OR ";
}
$sql = rtrim($sql, ') OR ');
$sql .= ")";


$profiles = queryDB("SELECT u.id, u.photo_1, u.name, u.business, u.date_added, l.city, l.state, l.zipcode FROM user_accounts as u INNER JOIN zipcodes as l ON u.zipcode = l.zipcode WHERE $sql ORDER BY date_added DESC", 'r');

1 个答案:

答案 0 :(得分:3)

来自其他question的@malias解释了hasrsine公式,这里有一个文档显示了提高此sql速度的不同方法:http://tr.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL

主要目标是限制搜索的zipcodes,这样您就不必计算这么多记录的半身像。建议是添加WHERE子句来过滤纬度和经度的边界。表索引可以用于此矩形过滤器,然后可以使用半字分过滤它作为球体。