我遇到mysql查询问题。我有一个带有ID(自动增量)的表,一个用户ID,一个值和以秒为单位的时间。现在我想得到每个用户的两个最低值的差异,但不知道如何做到:(
我有下表:
id | uid | myvalue | thetime
-----+-------+---------+-----------
13 | 1 | 120 | 1389287800
14 | 2 | 100 | 1389287810
15 | 3 | 110 | 1389287820
16 | 2 | 80 | 1389287830
17 | 4 | 100 | 1389287840
18 | 1 | 110 | 1389287850
19 | 3 | 105 | 1389287860
20 | 1 | 100 | 1389287870
我希望得到以下结果:
uid | difference --> Order by difference
-----+------------
2 | 20
1 | 10
3 | 5
如果有人出去帮助我,那就太好了。非常感谢!!
答案 0 :(得分:0)
你必须改进这一点,但这基本上就是你这样做的。你可以使用自我加入
SELECT uid, MAX(myvalue)-MIN(myvalue) AS diff FROM
(SELECT a.* FROM tablename AS a
LEFT JOIN tablename AS a2
ON a.uid=a2.uid AND a.myvalue<=a2.myvalue
GROUP BY uid,myvalue
HAVING COUNT(*)<=2
) a
GROUP BY uid