Another approach is to add a pivot table:
create table summary ( col varchar(10) primary key, items int not null );
and add triggers to tbl to:
insert:
insert into summary values( new.col, new.items ) on duplicate key update set summary.items = summary.items + new.items;
when deleting:
update summary set summary.items = summary.items - old.items where summary.col = old.col
when updating:
update summary set summary.items = summary.items - old.items where summary.col = old.col; update summary set summary.items = summary.items + new.items where summary.col = new.col;
This will slow down your insertions, but allow you to hit one row in the pivot table for
select items from summary where col = 'val';
The biggest problem with this is loading pivot table values. If you can disable the application, you can easily initialize the summary with the values ββfrom tbl.
insert into summary select col, sum(items) from tbl group by col;
However, if you need the service to work, it is much more complicated. If you have a replica, you can stop replication, create a pivot table, set triggers, restart replication, and then reinstall the service to use the replica, and then repeat the process on the retired primary.
If you cannot do this, you can update the pivot table one col value at a time to reduce the impact:
lock table write tbl, summary; delete from summary where col = 'val'; insert into summary select col, sum(items) from tbl where col = 'val'; unlock tables;
Or if you can endure a long break:
lock table write tbl, summary; delete from summary; insert into summary select col, sum(items) from tbl group by col; unlock tables;