我正在处理一个每分钟多次添加新行的表。正如我需要经常运行下面的查询一样,我认为这是最近延迟峰值的原因。
有什么方法可以让这个查询更高效吗?
SELECT IFNULL((SELECT SUM(amount)
FROM transactions
WHERE to_account=:account), 0) - IFNULL((SELECT SUM(amount)
FROM transactions WHERE from_account=:account), 0) as balance;
CREATE TABLE IF NOT EXISTS `transactions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`from_account` int(11) NOT NULL,
`to_account` int(11) NOT NULL,
`amount` int(11) unsigned NOT NULL,
`fee` int(11) NOT NULL DEFAULT '0'
`ip` varchar(39) DEFAULT NULL,
`time` int(10) NOT NULL,
`type` enum('CLAIM','REFERRAL','DEPOSIT','WITHDRAWAL') NOT NULL,
`is_processed` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `from_account` (`from_account`),
KEY `to_account` (`to_account`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=24099 ;
最佳答案
看起来您的两个表读取查询是
SELECT SUM(amount)
FROM transactions
WHERE from_account = constant
和
SELECT SUM(amount)
FROM transactions
WHERE to_account = constant
其中第一个可以通过 (from_account, amount) 上的复合索引进行优化,因为它允许通过索引范围扫描来满足查询。第二个查询可以用类似的索引来满足。您可以删除 from_account 和 to_account 上的索引,将其替换为这些复合索引。
INSERT 和 SELECT 查询之间仍然可能存在争用。但是 SELECT 的索引应该可以减少这种情况。
关于mysql - 减少查询的处理能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647391/