一尘不染

多对多关系的3个表之间的SQL查询

sql

我有三个表:friendslocationsfriend_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_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

任何建议将不胜感激。


阅读 154

收藏
2021-05-30

共1个答案

一尘不染

您可以执行以下操作:

SELECT  f.id, f.name, last_known_date, l.Lat, L.Lon
from Friends f
join
(
    select  f.id, MAX(l.Date) as last_known_date
    from    Friends f
    JOIN    Friend_Location fl on f.ID = fl.Friend_ID
    JOIN    Location l on l.ID = fl.Location_ID
    GROUP BY f.id
) FLMax
on FLMax.id = f.id
join Friend_Location fl on fl.friend_ID = f.ID
join Location l on fl.location_ID = l.ID AND l.Date = FLMax.Last_Known_Date

基本上,您的问题是您要按location.id分组,因为ID是唯一的,所以它将为您提供所有位置。

仅当朋友在任何一次只能位于1个位置时,此方法才有效。

2021-05-30