2017-01-01 105 views
0

数据库中,我有几百万结构行的表如下:将多行数以百万计

UserID | Date  | Points 
1  | 2016-05-01 | 240 
1  | 2016-05-02 | 500 
1  | 2016-05-03 | 650 
2  | 2016-05-01 | 122 
2  | 2016-05-02 | 159 
2  | 2016-05-03 | 290 

等等等等。

我需要找到Points之间的差异2016-05-032016-05-01之间的每个ID,按差异排序Points,并返回顶部~100。我的数据库包含数亿行,因此它需要快速操作。

我从哪里开始?我正在寻找group_concat,但我不确定这是否是这个用例的正确功能。

+0

是这些日期'2016年5月3日和2016-05-01'静态所有用户ID? – bhantol

+0

@bhantol他们,是的。每个用户将有一个日期的条目。 – DannyF247

+0

表有主键列吗? –

回答

0

此查询正在工作,它不是非常快速,但可以作出。

select tbl.id as UserId, ((select t.points from tbl t where date = '2016-05-03' and t.id=tbl.id)-(select t.points from tbl t where date = '2016-05-01' and t.id=tbl.id)) as diff from tbl group by id order by diff limit 100; 

运行这一点,让我知道,如果这是需要很长时间。

0

你应该有子查询像下面

SELECT 
    user_id, 
    (select points from tbl_test where tbl_test.date_of='2016-05-03' and user_id=t1.user_id)-t1.points as difference_in_points 
FROM `tbl_test` as t1 
WHERE date_of='2016-05-01' order by difference_in_points desc 
limit 100 
+0

这对你有帮助 –

0

加入表本身。

SELECT t1.user_id, t1.points - t2.points as diff 
FROM yourTable AS t1 
JOIN yourTable AS t2 ON t1.user_id = t2.user_id 
WHERE t1.date = '2016-05-03' 
AND t2.date = '2016-05-01' 
ORDER BY diff DESC 
LIMIT 100