我有一个包含数百万行的表,结构如下:
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-03
之间找到2016-05-01
对每个ID的差异,按Points
中的差异排序,然后返回前100个。我的数据库包含数亿行,因此需要快速操作。
我从哪里开始?我在看group_concat
,但我不确定这个用例是否正确。
答案 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;
运行此操作并告诉我这是否需要花费很多时间。
答案 1 :(得分: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
答案 2 :(得分: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