从 mysql 数据库多个表中获取最新记录

Get newest record out of mysql database multiple tables

我有三个 table。 一个包含用户详细信息:

---------------------------------
| Username | Phonenumber        |
---------------------------------
| user1    | 0000000000         |
---------------------------------
| user2    | 000000000          |
---------------------------------

表二包含联系信息,这是用户 "know" 彼此联系在一起的地方:

------------------------
| ID | User  | Friend  |
------------------------
| 1  | 1     | 2       |
------------------------
| 2  | 1     | 3       |
------------------------
| 3  | 3     | 2       |
------------------------

最后一个 table 包含位置信息:

----------------------------------------------------------
| ID | UserID  | TimeStamp         | Lng      | Lat      |
----------------------------------------------------------
| 1  | 1     | 2015-01-07 19:54:23 | lngvalue | latvalue |
----------------------------------------------------------
| 2  | 1     | 2015-01-07 19:54:26 | lngvalue | latvalue |
----------------------------------------------------------
| 3  | 2     | 2015-01-07 19:53:52 | lngvalue | latvalue |
----------------------------------------------------------

现在我想select用户1的好友的用户名和Phone号码,以及联系人用户的最新位置。

我创建了一个查询,但它显示了用户最旧的 lng/lat 值,而我需要最新的。

SELECT user.Username, user.PhoneNumber, location.Lng, location.Lat
FROM contact, user, location
WHERE User.ID IN (SELECT contact.Friend FROM contact WHERE contact.User = 1) 
AND user.ID = location.UserID
GROUP BY user.Username

基本思路:创建一个内联视图,查看所需的纬度和日志记录。然后加入其中。

SELECT user.Username, user.PhoneNumber, location.Lng, location.Lat
FROM contact, user, 
( select id, userid, max(timestamp) ts from location group by userid ) loc
, location
WHERE User.ID IN (SELECT contact.Friend FROM contact WHERE contact.User = 1) 
AND user.ID = loc.UserID
and location.id = loc.id
and location.timestamp = loc.ts
GROUP BY user.Username

我对来自 Randy 的查询做了一个小改动,因为我还可以通过检查位置 table 的最高 ID 来 select 最新记录。 对我有用的查询:

SELECT user.Username, user.PhoneNumber, location.Lng, location.Lat
FROM contact, user, 
( select max(id) maxid, userid from location group by userid ) loc
, location
WHERE User.ID IN (SELECT contact.Friend FROM contact WHERE contact.User = 1) 
AND user.ID = loc.UserID
and location.id = loc.maxid
GROUP BY user.Username