Počítanie v MySQL

ellaf

Počítanie v MySQL
« kdy: 11. 08. 2015, 18:22:12 »
Dobrý deň,

mam v mysql nasledujú tabuľku:
Kód: [Vybrat]
+----+---------+--------+-------+-------+
| id | user_id | points | order | total |
+----+---------+--------+-------+-------+
| 1  | 1       | 200    | 1     | 0     |
+----+---------+--------+-------+-------+
| 2  | 1       | 50     | 2     | 0     |
+----+---------+--------+-------+-------+
| 3  | 1       | -60    | 3     | 0     |
+----+---------+--------+-------+-------+
| 4  | 2       | 100    | 1     | 0     |
+----+---------+--------+-------+-------+
| 5  | 2       | 20     | 2     | 0     |
+----+---------+--------+-------+-------+

je tam cez 200k záznamov indexi sú na id - primary, user_id, order
môj problém je že neviem ako spočítať pre každého usera (total - ak je 0) = points - predchádzajúci total tak aby tabuľka vyzerala takto:

Kód: [Vybrat]
+----+---------+--------+-------+-------+
| id | user_id | points | order | total |
+----+---------+--------+-------+-------+
| 1  | 1       | 200    | 1     | 200   |
+----+---------+--------+-------+-------+
| 2  | 1       | 50     | 2     | 250   |
+----+---------+--------+-------+-------+
| 3  | 1       | -60    | 3     | 190   |
+----+---------+--------+-------+-------+
| 4  | 2       | 100    | 1     | 100   |
+----+---------+--------+-------+-------+
| 5  | 2       | 20     | 2     | 120   |
+----+---------+--------+-------+-------+

ťahať to do php a dávať update po jednom by bolo príšerne pomalé..nenapadá ma ako napísať takú query (alebo procedúru ?) v mysql

Za každú radu/riešenie by som bol vďačný.

« Poslední změna: 11. 08. 2015, 22:19:41 od Petr Krčmář »


k

Re:počítanie v mysql
« Odpověď #1 kdy: 11. 08. 2015, 18:47:22 »
Zkus to nějak takhle:

Kód: [Vybrat]
select id, user_id, points, order,
(select sum(total) from table tablex where tablex.user_id=table.user_id and tablex.id<=table.id) as total
from table
order by user_id, order

eL

Re:počítanie v mysql
« Odpověď #2 kdy: 11. 08. 2015, 20:38:06 »
set @csum := 0;
set @prevUser := 0;

SELECT  id, points, order,
  @csum := IF( @prevUser=`user_id`, @csum + points , points ) AS total,
  @prevUser := `user_id`

FROM `table`
ORDER BY `user_id`, order

Omezeni: ORDER BY musi byt jak, prirazeni prevUser musi byt az po csum

ellaf

Re:Počítanie v MySQL
« Odpověď #3 kdy: 12. 08. 2015, 00:45:49 »
Kód: [Vybrat]
set @csum := 0;
set @prevUser := 0;

update test as t1,
(

SELECT  id, points, order,
  @csum := IF( @prevUser=`user_id`, @csum + points , points ) AS total,
  @prevUser := `user_id`

FROM `test`
ORDER BY `user_id`, order) as t2
set t1.total = t2.total
where t1.id = t2.id

ďakujem, funkčne :)