friends
、locations
、 の3 つのテーブルがあります。friend_location
friend_location
は、 と の間の多対多の関係を可能にする結合テーブルfriends
でlocations
あるため、テーブルは次のようになります。
友達
ID | Name
1 | Jerry
2 | Nelson
3 | Paul
位置
ID | Date | Lat | Lon
1 | 2012-03-01 | 34.3 | 67.3
2 | 2011-04-03 | 45.3 | 49.3
3 | 2012-05-03 | 32.2 | 107.2
友達の場所
Friend_ID | Location_id
1 | 2
2 | 1
3 | 3
2 | 2
私がやりたいのは、各友達の最新の場所を取得することです。
結果
ID | Friend | Last Know Location | last know date
1 | Jerry | 45.3 , 49.3 | 2011-04-03
2 | Nelson | 34.3 , 67.3 | 2012-03-01
3 | Paul | 32.2 , 107.2 | 2012-05-03
これは、さまざまな例を見て試したものですが、多くの結果に戻り、正しくありません。
select f.id , f.name , last_known_date
from friends f, (
select distinct fl.friend_id as friend_id, fl.location_id as location_id, m.date as last_known_date
from friend_location fl
inner join (
select location.id as id, max(date) as date
from location
group by location.id
) m
on fl.location_id=m.id
) as y
where f.id=y.friend_id
どんな提案でも大歓迎です。