Fórum Root.cz
Hlavní témata => Vývoj => Téma založeno: ellaf 11. 08. 2015, 18:22:12
-
Dobrý deň,
mam v mysql nasledujú tabuľku:
+----+---------+--------+-------+-------+
| 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:
+----+---------+--------+-------+-------+
| 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ý.
-
Zkus to nějak takhle:
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
-
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
-
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 :)