我有三個表:friends
,locations
,friend_location
SQL查詢一個多一對多的關係
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_location
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
任何建議,將不勝感激。
請列出您正在使用的數據庫的類型...這很大程度上影響了答案,因爲窗口函數使事情變得簡單和簡潔(但在所有數據庫中都不可用)。 – 2012-07-30 03:29:15
您可能需要考慮將最後一個已知日期轉換爲單獨的表格 – cordialgerm 2012-07-30 04:51:39
使用PostgrisSQL。謝謝。 – Cysneros 2012-07-30 06:01:11