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

时间:2015-01-07 19:41:57

标签: php mysql

我有三张桌子。 一个用户详细信息:

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

表2包含联系信息,这是用户在彼此“了解”时链接在一起的地方:

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

最后一个,一个包含位置信息的表:

----------------------------------------------------------
| 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 |
----------------------------------------------------------

现在我想从用户1的朋友中选择用户名和电话号码,以及联系人用户的最新位置。

我创建了一个查询,但它显示了用户最早的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

2 个答案:

答案 0 :(得分:1)

我对Randy的查询做了一些小改动,因为我也可以通过检查位置表中的最高ID来选择最新的记录。 该查询对我有用:

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

答案 1 :(得分:0)

基本思路:创建所需的lat和日志记录的内联视图..然后加入到那个。

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