說我有3個表,像這樣:MySQL的選擇最近的位置僅當也最新的位置
cities
------
name
latitude
longitude
stalls
------
id
name
locations
---------
stall_id
latitude
longitude
date
我想找到在過去的6個月內最近的攤位一個城市。這部分是好的 - 我查詢攤位/位置表,並使用Haversine在距離內。都好。
這是我當前的查詢:
SELECT stalls.name, (3959 * acos(cos(radians($lat)) * cos(radians(locations.lat)) * cos(radians(locations.lng) - radians($lng)) + sin(radians($lat)) * sin(radians(locations.lat)))) AS distance
FROM locations
LEFT JOIN stalls ON stalls.id = locations.trader_id
WHERE locations.added > $date
HAVING distance < 10
然而,有可能爲一檔,以在不同城市的多個新的位置,我只想匹配一個城市的最新位置。 例如一個攤位可能會匹配作爲最接近紐約,但然後爲洛杉磯添加一個新的位置。現在它只能在洛杉磯顯示6個月而不顯示紐約 - 至少在添加另一個位置之前。以前的位置需要存儲,所以我不能清除這些。
在查詢中執行此操作的最佳方法是什麼?
您應該顯示您擁有的查詢。 –
我已添加查詢 – Wazzbast
請參閱:[爲什麼我應該爲我認爲是非常簡單的SQL查詢提供一個MCVE?](https://meta.stackoverflow.com/questions/333952/why-should-我提供了一個mcve爲什麼似乎對我來說是一個非常簡單的sql查詢) – Strawberry