SQL需要建议如何为此查询添加时间戳

时间:2013-04-23 17:49:28

标签: sql

我有这段代码:

    select Users.phoneMac, Users.apMac, Locations.Lon, Locations.Lat
    from Locations, Users
    inner join (
    select u.phoneMac, max(u.strenght) as most
    from Users u, Locations l
    where u.apMac = l.apMac
    group by u.phoneMac
    ) as ij on ij.phoneMac=Users.phoneMac and Users.strenght = ij.most 
    where Locations.apMac = Users.apMac;

它很适合我,但当我向用户表添加更多数据时,此查询计算了所有数据的结果,我想从最新数据中获得结果。所以我在Users表中添加了时间戳。

那么你可以帮我修复这段代码吗?所以它首先只为每个用户(users.phoneMac)提供最新时间戳的数据(同一个phoneMac可以有超过1行的数据),然后进行其余的计算。

1 个答案:

答案 0 :(得分:1)

您已经在选择“实力”字段的最大值并加入其中,那么为什么不再对您的时间戳字段使用相同的方法呢?类似的东西:

SELECT Users.phoneMac, Users.apMac, Locations.Lon, Locations.Lat
FROM Locations
INNER JOIN Users
ON Users.apMac = Locations.apMac
INNER JOIN (
 SELECT u.phoneMac, max(u.strenght) AS most
 FROM Locations l
 INNER JOIN Users u ON u.apMac = l.apMac
 GROUP BY u.phoneMac) AS ij
ON ij.phoneMac = Users.phoneMac
AND Users.strenght = ij.most
INNER JOIN (
 SELECT u2.phoneMac, max(u2.timestampfield) AS latest
 FROM Locations l2
 INNER JOIN Users u2 ON u2.apMac = l2.apMac
 GROUP BY u2.phoneMac) AS ijk
ON ijk.phoneMac = Users.phoneMac
AND Users.timestampfield = ij.latest;

(顺便说一句,使用带有逗号和WHERE子句的旧连接语法会使逻辑更难理解,偶尔会使逻辑错误。使用ON的新连接语法实际上要好得多。)