我有三个表:friends
,locations
,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_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
任何建议都将不胜感激。
答案 0 :(得分:2)
你可以这样做:
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个位置的情况。
答案 1 :(得分:2)
Gregs查询对我来说是正确的,我想出了类似的(见下文)。但是,当两个朋友以不同顺序访问相同位置时,当前的db模式不处理这种情况。对我来说,似乎Date列应该在friend_location表中,而不是位置。但是,如果不是,那么查询是:
SELECT F.ID, F.Name AS Friend, L.Lat, L.Lon, L.Date
FROM
(
SELECT MAX(L.date) AS max_date, F.ID
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
) AS X
JOIN Friends F ON X.ID=F.ID
JOIN friend_location FL ON F.ID=FL.Friend_ID
JOIN location L ON L.ID=FL.Location_id AND L.Date=X.max_date
答案 2 :(得分:1)
您的数据布局有点奇怪,因为日期位于位置表中。因此,以下内容检索每位朋友的最新日期:
select fl.friend_id, max(l.date) as maxdate
from friend_location fl
location l join
on fl.location_id = l.location_id
现在,让我们重新加入此查询的信息:
select f.*, maxdate, l.*
from (select fl.friend_id, max(l.date) as maxdate
from friend_location fl
JOIN location l
on fl.location_id = l.id
group by fl.friend_id
) flmax join
friends f
on flmax.friend_id = f.id
join location l
on l.date = flmax.maxdate
这将起作用,假设位置没有重复日期。如果他们这样做,查询会更复杂一些。我们可以做出这个假设吗?
答案 3 :(得分:1)
您可以使用:
SELECT
a.*,
CONCAT(d.Lat, ' , ', d.Lon) AS last_known_location,
d.Date AS last_known_date
FROM
friends a
JOIN
(
SELECT a.Friend_ID, MAX(b.Date) AS maxdate
FROM friend_location a
JOIN location b ON a.Location_id = b.ID
GROUP BY a.Friend_ID
) b ON a.ID = b.Friend_ID
JOIN
friend_location c ON b.Friend_ID = c.Friend_ID
JOIN
location d ON c.Location_id = d.ID AND b.maxdate = d.Date