0

我有这个代码:

    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.phoneMac)(同一个phoneMac可以有超过1行数据),然后进行其余的计算。

4

1 回答 1

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 确实好多了。)

于 2013-04-23T18:18:04.837 回答