作为加载基准,MySQL 查询真的很慢

标签 mysql sql database

在某些 WHEREHAVING 条件下,我从这个 MySQL 查询中遇到了一个非常缓慢的加载基准:

  SELECT * FROM test p 
  WHERE p.brandid=636  
    AND DATEDIFF(p.registration, '2019-01-01') >= 0 
    AND DATEDIFF(p.registration, '2019-05-22') <= 0  
  GROUP BY p.invoice_num 
  HAVING (p.net_amount BETWEEN 0 AND 1000) 
    AND (p.profit_amount BETWEEN 0 AND 1000) 
    AND (p.cost_amount BETWEEN 0 AND 1000) 
  ORDER BY p.registration DESC LIMIT 100 OFFSET 0

在 CREATE STMT 下方:

CREATE TABLE `test` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `original_id` bigint(11) DEFAULT NULL,
  `invoice_num` bigint(11) NOT NULL,
  `registration` timestamp NULL DEFAULT NULL,
  `paid_amount` decimal(10,6) DEFAULT NULL,
  `cost_amount` decimal(10,6) DEFAULT NULL,
  `profit_amount` decimal(10,6) DEFAULT NULL,
  `net_amount` decimal(10,6) DEFAULT NULL,
  `customer_id` bigint(11) DEFAULT NULL,
  `recipient_id` text,
  `cashier_name` text,
  `sales_type` text,
  `sales_status` text,
  `sales_location` text,
  `invoice_duration` text,
  `store_id` double DEFAULT NULL,
  `is_cash` int(11) DEFAULT NULL,
  `is_card` int(11) DEFAULT NULL,
  `brandid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`,`invoice_num`),
  KEY `idx_registration_compound` (`id`,`registration`),
  KEY `invoiceNum_idx` (`invoice_num`)
) ENGINE=InnoDB AUTO_INCREMENT=47420958 DEFAULT CHARSET=latin1;

我在 idregistration 字段之间添加了一个复合索引。但我认为我可以通过更正确的索引组合来改进它。

解释下方: enter image description here

TIMEDIFF() 是性能问题吗? 关于如何改进基准的任何想法?

最佳答案

您的 where 子句涉及列 brandid (p.brandid=636) 和 p.registration (DATEDIFF(p.registration, '2019-01-01')) 因此请尝试在

上添加复合索引
table  test  columns  ( brandid, registration) 

关于作为加载基准,MySQL 查询真的很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56256776/

相关文章:

mysql - SQL - 如何自动选择 1 到 1000 之间剩余的最小 id

HTML 实体解码为特殊字符

sql - 在 BigQuery 中随机抽样替换的最有效方法是什么?

mysql - SQL:如何根据可交换列聚合多行?

php - 为新行轮询 MySQL 表的最快方法是什么?

php - MySQL 表名带有重音符号。通过 PDO 更新时出现无效的 utf8 字符串

PHP MYSQL删除语法错误

sql - 检查数据是否已存在并插入的更好方法

database - 如何在git中保留文件权限?

php - mysql表中的最大数据