mysql - 减少查询的处理能力

标签 mysql database performance processing-efficiency

我正在处理一个每分钟多次添加新行的表。正如我需要经常运行下面的查询一样,我认为这是最近延迟峰值的原因。

有什么方法可以让这个查询更高效吗?

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/

相关文章:

php - 使用 mysql 表从 php 创建饼图

php - 在外键名称中添加 _id"后缀的好处

php - 将内容限制为前 10 位用户的最佳方法是什么(可能使用 PHP 和 MySQL)?

c - 我们如何为变量指定物理地址?

mysql - 找出另一列的值与哪一列匹配

database - 将 MongoDB compass 连接到另一台机器上运行的 MongoDB

android - 如何从远程数据库获取错误报告?

c++ - 选择语句和隐式转换只给我字符串的第一个字符

performance - 减少 Visual Studio 构建时间

c++ - 使用 Apple Accelerate Framework vForce 库提高性能