SQL错误:每个派生表都必须有自己的别名

时间:2013-08-31 19:53:30

标签: php mysql sql zipcode

我知道有很多问题可以解决这个错误,但我已经完成了他们要求解决的问题。以下是我所做的但我仍然得到错误。此脚本的目标是显示特定半径内的所有zipcodes。

$zip = 94550; // "find nearby this zip code"
$radius = 15; // "search radius (miles)"
$maxresults = 10; // maximum number of results you'd like

$sql = "SELECT * FROM
    (SELECT o.zipcode, o.city, o.state,
        (3956 * (2 * ASIN(SQRT(
        POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
        COS(z.latitude*0.017453293) *
        COS(o.latitude*0.017453293) *
        POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
        )))) AS distance
    FROM zipcoords z,
        zipcoords o,
        zipcoords a
    WHERE z.zipcode = ".$zip." AND z.zipcode = a.zipcode AND
        (3956 * (2 * ASIN(SQRT(
        POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
        COS(z.latitude*0.017453293) *
        COS(o.latitude*0.017453293) *
        POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
        )))) <= ".$radius."
    ORDER BY distance)
    ORDER BY distance ASC LIMIT 0,".$maxresults;

$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());   

while ($ziprow = mysql_fetch_array($result)) {
$zipcode = $ziprow['zipcode'];
echo "$zipcode<br>";
}

数据库中的所有列都是varchar。 zipcode是主要的,我会使它INT,但它不允许在zipcodes的开头有0。所以我把它改成了varchar并允许它。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

$sql = "SELECT * FROM
    (SELECT o.zipcode, o.city, o.state,
        (3956 * (2 * ASIN(SQRT(
        POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
        COS(z.latitude*0.017453293) *
        COS(o.latitude*0.017453293) *
        POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
        )))) AS distance
    FROM zipcoords z,
        zipcoords o,
        zipcoords a
    WHERE z.zipcode = ".$zip." AND z.zipcode = a.zipcode AND
        (3956 * (2 * ASIN(SQRT(
        POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
        COS(z.latitude*0.017453293) *
        COS(o.latitude*0.017453293) *
        POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
        )))) <= ".$radius."
    ORDER BY distance) AS random_word_to_silence_that_error
    ORDER BY distance ASC LIMIT 0,".$maxresults;

我添加了random_word_to_silence_that_error,因为在您的情况下,我认为它不会用于其他目的。

答案 1 :(得分:1)

选择FROM子查询时必须使用别名。

请参阅:http://dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html

只需在您选择的子查询末尾添加AS <alias name>

...
ORDER BY distance) AS SOME_ALIAS
ORDER BY distance ASC LIMIT 0
...