此MySQL查询在某些WHERE
和HAVING
条件下正在经历非常缓慢的加载基准:
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;
我在id
和registration
字段之间添加了复合索引。但是我认为我可以通过更正确地结合索引来改进它。
TIMEDIFF()是否对性能有影响? 关于如何提高基准的任何想法?
答案 0 :(得分:1)
您的where子句涉及列brandid(p.brandid = 636)和p.registration(DATEDIFF(p.registration,'2019-01-01')),因此请尝试在
上添加一个复合索引table test columns ( brandid, registration)
答案 1 :(得分:1)
根据建议,使用(品牌标识,注册)和
尝试将力索引与新创建的复合索引一起使用
从逻辑上讲,您的查询可以重组为
SELECT * FROM test p force index (index_name)
WHERE p.brandid=636
AND p.registration between '2019-01-01' and '2019-05-22'
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
尝试运行此命令并共享解释结果集