gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:08:34 26 4
gpt4 key购买 nike

我有三张表:friends , locations , friend_locationfriend_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

我想做的是获取每个 friend 的最新位置。

结果

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

任何建议将不胜感激。

最佳答案

你可以这样做:

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 是唯一的。

这仅适用于 friend 在任何 1 次只能位于 1 个位置的情况。

关于多对多关系的 3 个表之间的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11714711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com