2014-01-13 167 views
0

我們對MYTABLE有此查詢,並想加入OTHER_TABLE以從中獲取鏈接數據。但它似乎並不奏效。MYSQL add JOIN to query

SELECT *,3956 * 2 * ASIN(SQRT(POWER(SIN(($orig_lat - abs(wlatitude)) * pi()/180/2),2) 
+ COS($orig_lat * pi()/180) * COS(abs(wlatitude) * pi()/180) * POWER(SIN(($orig_lon - wlongitude) * pi()/180/2), 2))) 
as distance FROM MYTABLE dest having distance < $dist ORDER BY distance 

我們如何將這個添加到查詢中而不會出錯?

LEFT JOIN OTHER_TABLE ON MYTABLE.column=OTHER_TABLE.column 
+0

只是把它蒸餾水和其之間,並使用您所創建的別名。 '左加入OTHER_TABLE ON dest。 = ot。 ' –

回答

0

使用左連接可能有可能獲得重複嘗試這種使用不同也使用適當的別名表

SELECT DISTINCT 
    *, 
    3956 * 2 * ASIN(
    SQRT(
     POWER(
     SIN(
      ($orig_lat - ABS(dest.wlatitude)) * PI()/180/2 
     ), 
     2 
    ) + COS($orig_lat * PI()/180) * COS(ABS(dest.wlatitude) * PI()/180) * POWER(
     SIN(($orig_lon - dest.wlongitude) * PI()/180/2), 
     2 
    ) 
    ) 
) AS distance 
FROM 
    MYTABLE dest 
    LEFT JOIN OTHER_TABLE o ON dest.column=o.column 
HAVING distance < $dist 
ORDER BY distance 
0

還沒有深入您的查詢,但它應該是這樣的。

SELECT 
    *, 
    3956 * 2 * ASIN(SQRT(POWER(SIN(($orig_lat - abs(wlatitude)) * pi()/180/2),2) + COS($orig_lat * pi()/180) * COS(abs(wlatitude) * pi()/180) * POWER(SIN(($orig_lon - wlongitude) * pi()/180/2), 2))) 
     as distance 
FROM MYTABLE dest 
LEFT JOIN OTHER_TABLE ON MYTABLE.column=OTHER_TABLE.column 
HAVING distance < $dist 
ORDER BY distance 
0
SELECT *, 3956 * 2 * ASIN(SQRT(POWER(SIN(($orig_lat - abs(wlatitude)) * pi()/180/2),2) 
+ COS($orig_lat * pi()/180) * COS(abs(wlatitude) * pi()/180) * POWER(SIN(($orig_lon - wlongitude) * pi()/180/2), 2))) AS distance 
FROM MYTABLE dest 
LEFT JOIN OTHER_TABLE ON dest.column = OTHER_TABLE.column 
HAVING distance < $dist ORDER BY distance 
1

不管你會做什麼,你不會得到「錯誤」而導致也許你並不需要。

如果連接是1對1或多對一,則不會得到任何相乘的行。

如果連接是一對多的,則根據您的條件,右側的每個相應行的數量可能會在左側乘倍。

查看http://en.wikipedia.org/wiki/Relational_algebra#Joins_and_join-like_operators的連接邏輯。

到您的查詢,以及其他任何的查詢中,趙彤順序是:

select # ... 
from # table 
join # table 
on # condition 
join # another table 
on # another condition 
where # condition 
group # clause 
having # condition applied after grouping 
order by # ..