我試圖找到距離用戶最近的故事。但是,只有我們故事中的章節有位置,所以我需要獲取這些專案,然后從該串列中獲取最近的章節,然后根據已檢索到的距離對故事進行排序。這里的硬編碼數字僅用于測驗/示例,將在查詢時動態替換為用戶的位置。
我創建了一個讓我非常接近的函式,但它為每一章有多個條目,而不是每個故事都使用與章節的最小距離值。
select
story.id,
story.name,
earth_distance(ll_to_earth(place.longitude, place.latitude), ll_to_earth(153.03563, -27.38223)) as distance
from story
inner join chapter on chapter.story_id = story.id
inner join place on chapter.place_id = place.id
order by distance
我有一個查詢,它為我提供了所有章節中的最小章節距離:
select MIN (earth_distance(ll_to_earth(place.longitude, place.latitude), ll_to_earth(153.03563, -27.38223))) as distance
from chapter
left join place on chapter.place_id = place.id
這按預期作業。
我玩了這個的子選擇版本,它說距離沒有定義:
select
story.id,
distance
from story
where
distance = (
select MIN (earth_distance(ll_to_earth(place.longitude, place.latitude), ll_to_earth(153.03563, -27.38223))) as distance
from chapter, place
where chapter.story_id = story.id
and chapter.place_id = place.id
);
有沒有辦法將這些組合或使用在一起,讓我按距離排序每個故事?
uj5u.com熱心網友回復:
你可以試試這個:
select
story.id,
story.name,
min(earth_distance(ll_to_earth(place.longitude, place.latitude), ll_to_earth(153.03563, -27.38223))) as distance_min
from story
inner join chapter on chapter.story_id = story.id
inner join place on chapter.place_id = place.id
group by story.id, story.name
order by distance_min
limit 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403723.html
標籤:
上一篇:匹配2個串列的順序值
