Problem:
MySQL queries to count the number of rows in a large table or group them by a particular column can become slow as the table grows. Even indexing the column used for grouping doesn't consistently improve performance.
Exploration:
To optimize these queries, alternative approaches without using caching include:
Implementation:
For maintaining a summary table, the following boilerplate triggers can be used:
DELIMITER // CREATE TRIGGER ai_books AFTER INSERT ON books FOR EACH ROW UPDATE books_cnt SET total = total + 1 WHERE status = NEW.status // CREATE TRIGGER ad_books AFTER DELETE ON books FOR EACH ROW UPDATE books_cnt SET total = total - 1 WHERE status = OLD.status; // CREATE TRIGGER au_books AFTER UPDATE ON books FOR EACH ROW BEGIN IF (OLD.status <> NEW.status) THEN UPDATE books_cnt SET total = total + IF(status = NEW.status, 1, -1) WHERE status IN (OLD.status, NEW.status); END IF; END //
By maintaining a summary table, row counting queries can be executed much faster, regardless of the table size.
The above is the detailed content of How Can I Speed Up Row Counting Queries in Large MySQL Tables?. For more information, please follow other related articles on the PHP Chinese website!