我有三个表。 一个包含用户详细信息:
---------------------------------
| Username | Phonenumber |
---------------------------------
| user1 | 0000000000 |
---------------------------------
| user2 | 000000000 |
---------------------------------
表二包含联系信息,这是用户“认识”彼此时链接在一起的地方:
------------------------
| 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的 friend 中选择用户名和电话号码,以及联系人用户的最新位置。
我创建了一个查询,但它向我显示了用户最早的 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
最佳答案
我对来自 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
关于php - 从mysql数据库多表中获取最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27827352/