MySql嵌套选择和内连接

时间:2013-10-24 09:53:56

标签: mysql nested inner-join

我现有的搜索工作正常。它正在搜索表1(俱乐部),但需要从表2(城镇)获得一些数据。为此,它执行两个表的INNER JOIN。

我现在正试图将结果限制在距离某一点一定距离内的结果。

两个表都有称为纬度和经度的字段,但只填充了Towns值,因此我需要在搜索中使用这些值。

其他几个字段在两个表中使用相同的名称,因此我必须指出我的意思(例如,Towns.town_key)。

要进行距离搜索,我在内部嵌套中进行粗略的方框搜索,然后在外部嵌套中对其结果进行毕达哥拉斯公式。 (我不需要Haversine的准确性。)

无论我尝试什么,我都会在前面有表名的字段上遇到错误。不幸的是,尽管有很多阅读,但我并不完全理解别名的使用等。

这是我的搜索:

SELECT club_key, name, Towns.town_key, town_name, Clubs.address,
sqrt(((-32.380100 - Towns.latitude)*111.133)^2 + ((147.481400 - 
Towns.longitude)*93.853)^2) AS dist FROM 

(SELECT club_key, name, Towns.town_key, town_name, Clubs.address FROM Clubs 

INNER JOIN Towns ON Clubs.town_key = Towns.town_key WHERE type = 'football' 
AND Towns.latitude BETWEEN -32.829761 AND -31.930439 AND Towns.longitude BETWEEN 146.948951 AND 148.013849) AS T1 

WHERE dist < 50 ORDER BY 6,2

最新的错误是: 无法运行查询:'字段列表'中的未知列'Towns.town_key'

在此之前,它反对纬度和经度字段,这些字段在内部和外部选择中都使用。

2 个答案:

答案 0 :(得分:1)

这里的问题是别名的范围。放手一搏:

SELECT T1.club_key, T1.name, T1.town_key, T1.town_name, T1.address,T1.dist
FROM 
(
SELECT
sqrt(((-32.380100 - Towns.latitude)*111.133)^2 + ((147.481400 - 
Towns.longitude)*93.853)^2) AS dist, 
club_key, name, Towns.town_key, town_name, Clubs.address 
FROM Clubs 
INNER JOIN Towns ON Clubs.town_key = Towns.town_key 
WHERE type = 'football' 
AND Towns.latitude BETWEEN -32.829761 AND -31.930439 
AND Towns.longitude BETWEEN 146.948951 AND 148.013849
) AS T1 
WHERE T1.dist < 50 ORDER BY 6,2

您正在尝试使用嵌套选择之外的别名,即引用嵌套选择内的表的Towns,即Towns表。您可以使用T1别名来解决此问题。

答案 1 :(得分:0)

SELECT  
    T1.club_key, 
    T1.name, 
    T1.town_key, 
    T1.town_name, 
    T1.address,
    sqrt(((-32.380100 - T1.latitude)*111.133)^2 + ((147.481400 - T1.longitude)*93.853)^2) AS dist 
FROM 
(
    SELECT 
        Towns.latitude,
        Towns.longitude,
        club_key, 
        name, 
        Towns.town_key, 
        town_name, 
        Clubs.address 
    FROM Clubs 
    INNER JOIN Towns ON Clubs.town_key = Towns.town_key 
    WHERE 
        type = 'football' 
        AND Towns.latitude BETWEEN -32.829761 AND -31.930439 
        AND Towns.longitude BETWEEN 146.948951 AND 148.013849
) AS T1 
HAVING dist < 50 
ORDER BY 6,2

在上一个答案中,我认为它们不起作用,而不是你必须使用HAVING