我有三个表:friends,locations,friend_location% S, i8 f$ _8 a# x6 P4 F; I. x
friend_location允许使用联接表friends多对多关系locations,因此,这些表将如下所示: - H K& N7 j7 t. a V3 _2 T朋友们5 o( e) @2 {$ _9 n0 ~/ `
ID | Name1 | Jerry2 | Nelson3 | Paul地点! J, z5 T' J: J1 o
ID | Date | Lat | Lon 1 | 2012-03-01 | 34.3 | 67.32 | 2011-04-03 | 45.3 | 49.33 | 2012-05-03 | 32.2 | 107.2friend_location 1 x& _+ m" k/ l6 S WFriend_ID | Location_id1 | | | | 2我想做的就是获得每个朋友的最新位置。/ ^8 n1 Y% t1 q: _2 i n 结果7 `+ v3 w) B! {1 E$ J: L) U
ID | Friend | Last Know Location | last know date1 | Jerry | 45.3 ,49.3 | 2011-04-032 | Nelson | 34.3 ,67.3 | 2012-03-013 | Paul | 32.2 ,107.2 | 2012-05-03这是我在查看各种示例之后尝试过的方法,但是它返回了许多结果,并且是不正确的:0 ~8 I* R$ Y0 } l1 B
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感谢任何建议。- R$ K: _) \* Y6 }4 l" m, _
! n% t0 ]( Q1 F$ [$ b解决方案: 5 P( }/ |% f5 \8 Y( @% q 可执行以下操作:; s& z7 X9 b) x+ g( E' S
SELECT f.id,f.name,last_known_date,l.Lat,L.Lonfrom Friends fjoin( 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) FLMaxon FLMax.id = f.idjoin Friend_Location fl on fl.friend_ID = f.IDjoin Location l on fl.location_ID = l.ID AND l.Date = FLMax.Last_Known_Date基本上,你的问题是你必须遵循location.id分组,因为ID它是唯一的,所以它会为你提供所有的位置。8 f3 H! G& h# B/ q4 A' v
这种方法只有在朋友一次只能在一个位置时才有效。