如何在mysql中找到更大的增值

时间:2015-04-06 21:00:26

标签: php mysql mysqli

我有一张历史表

user  | point | date 
john  | 100   | 2015-01-01 
smith | 90    | 2015-01-01 
adam  | 95    | 2015-01-01 
john  | 120   | 2015-01-02 
smith | 115   | 2015-01-02 
adam  | 105   | 2015-01-02
john  | 125   | 2015-01-03 
smith | 120   | 2015-01-03 
adam  | 135   | 2015-01-03

在此表中,我想找到在表的最后3天按增加点排序的用户列表,因此输出将为:

adam  | 40
smith | 30
john  | 25

我怎么能用php和mysql做到这一点?

2 个答案:

答案 0 :(得分:1)

一种方法是使用表的自联接,指定开始和结束日期。

SELECT t1.user, t1.point - t2.point AS diff
FROM yourTable AS t1
JOIN yourTable AS t2 ON t1.user = t2.user
WHERE t1.date = '2015-01-03'
AND t2.date = '2015-01-01'
ORDER BY diff DESC

答案 1 :(得分:1)

你可以在MySQL中单独使用这样的东西。

select user,(max(point) - min(point)) diff
from your_table
where date > ( CURDATE() - INTERVAL 3 DAY )
group by user
order by diff desc