在某些 WHERE
和 HAVING
条件下,我从这个 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;
我在 id
和 registration
字段之间添加了一个复合索引。但我认为我可以通过更正确的索引组合来改进它。
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/