2016-07-05 161 views
0

我讀過,加入請求通常是更有效的子查詢。Mysql子查詢轉換內部聯接

我想知道下面的查詢是否可以轉換爲加入。 Personnaly,我不明白這是如何可能的。

只是爲了讓您知道,距離的計算是昂貴的,我只是想在子集(子查詢的結果)上執行它。但是,外部查詢並沒有保留「order by」。這就是爲什麼我必須在外部查詢中執行第二個命令。

有沒有辦法做得更好?

SELECT alias.*, [calculation of distance using table cities] AS distance 
FROM (SELECT item.* FROM item 
     WHERE item.postalCode IN ([Array of postal codes]) 
     ORDER BY item.creationTimestamp ASC LIMIT 0, 19) as myalias, 
     country_cities 
WHERE cities.postalCode = alias.postalCode 
ORDER BY myalias.creationTimestamp ASC 

回答

0

你可以改變它TO INNER JOIN如下

SELECT alias.*, [calculation of distance using table cities] AS distance 
FROM (SELECT item.* FROM item 
     WHERE item.postalCode IN ([Array of postal codes]) 
     ORDER BY item.creationTimestamp ASC LIMIT 0, 19) myalias INNER JOIN country_cities 
WHERE cities.postalCode = alias.postalCode 
ORDER BY myalias.creationTimestamp ASC