我遇到了SQL(MySql)查询的性能问题。基本上我有一个类似这样的表:
ID PRICE ID OBJECT
-----------------------------
1 500.00 1 1
2 300.00 1 1
3 400.00 1 1
4 100.00 1 1
5 100.00 1 1
6 100.00 2 3
我需要获得给定金额的最大行数。
例如,给定金额1000.00,查询必须返回这些ID(按价格asc排序)和总价格。
ID PRICE TOTAL_PRICE
---------------------------------
4 100 100.00
5 100 200.00
2 300 500.00
3 400 900.00
Atm我正在使用类似下面的查询:
set @total=0;
select a.id, a.price , @total:=@total + a.price as total_price , a.id_user
from shares a
where a.`id_user` != 0 and a.id_object = 1
having @total < 1000.00 order by a.price asc;
它工作正常,但效率不高。提取数据大约需要1.5秒(表格大约有1M行)。
问题与Having子句有关。
你有什么建议吗?
有没有办法使用拥有这个
的来执行此类查询答案 0 :(得分:0)
我相信这(cumulative sum
)正是您所寻找的:
set @total = 0;
SELECT ID,
Price,
Total_Price
FROM (
SELECT a.*
,(@total := @total + price) AS total_price
FROM shares a
WHERE a.id_user != 0
AND a.id_object = 1
ORDER BY a.price
) q1
WHERE q1.total_price < 1000;