数据库
首页 > 数据库> > 更好的MySQL查询性能

更好的MySQL查询性能

作者:互联网

我希望得到一个项目#QTYs的SUM分组为几个月,查询需要太长时间(15 – 20)秒才能获取.

– 总行数:1495873
-Total Fetched rows:9 – 12

两个表(invoice_header和invoice_detail)之间的关系是(一对多),invoice_header是发票的标题,只有总计.使用位置ID(loc_id)和发票编号(invo_no)链接到invoice_detail,因为每个位置都有自己的序列号.发票明细包含每张发票的详细信息.

有没有更好的方法来增强该查询的性能,这里是:

SELECT SUM(invoice_detail.qty) AS qty, Month(invoice_header.date) AS month
FROM invoice_detail
JOIN invoice_header ON invoice_detail.invo_no = invoice_header.invo_no
AND  invoice_detail.loc_id = invoice_header.loc_id
WHERE invoice_detail.item_id = {$itemId}
GROUP BY Month(invoice_header.date)
ORDER BY Month(invoice_header.date)

说明:

invoice_header表结构:

CREATE TABLE `invoice_header` (
 `invo_type` varchar(1) NOT NULL,
 `invo_no` int(20) NOT NULL AUTO_INCREMENT,
 `invo_code` varchar(50) NOT NULL,
 `date` date NOT NULL,
 `time` time NOT NULL,
 `cust_id` int(11) NOT NULL,
 `loc_id` int(3) NOT NULL,
 `cash_man_id` int(11) NOT NULL,
 `sales_man_id` int(11) NOT NULL,
 `ref_invo_no` int(20) NOT NULL,
 `total_amount` decimal(19,2) NOT NULL,
 `tax` decimal(19,2) NOT NULL,
 `discount_amount` decimal(19,2) NOT NULL,
 `net_value` decimal(19,2) NOT NULL,
 `split` decimal(19,2) NOT NULL,
 `qty` int(11) NOT NULL,
 `payment_type_id` varchar(20) NOT NULL,
 `comments` varchar(255) NOT NULL,
 PRIMARY KEY (`invo_no`,`loc_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20286 DEFAULT CHARSET=utf8

invoice_detail表结构:

CREATE TABLE `invoice_detail` (
 `invo_no` int(11) NOT NULL,
 `loc_id` int(3) NOT NULL,
 `serial` int(11) NOT NULL,
 `item_id` varchar(11) NOT NULL,
 `size_id` int(5) NOT NULL,
 `qty` int(11) NOT NULL,
 `rtp` decimal(19,2) NOT NULL,
 `type` tinyint(1) NOT NULL,
 PRIMARY KEY (`invo_no`,`loc_id`,`serial`),
 KEY `item_id` (`item_id`),
 KEY `size_id` (`size_id`),
 KEY `invo_no` (`invo_no`),
 KEY `serial` (`serial`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

解决方法:

遵循SQL需要多长时间?

SELECT count(*)
FROM invoice_detail
WHERE invoice_detail.item_id = {$itemId}

如果此SQL需要15-20秒,则应在inovice_detail表的字段item_id上添加索引.

invoice_header已在invo_no和loc_id的连接列上拥有主键,因此您无需在invoice_header表上添加其他索引.但是如果你在字段invo_no,loc_id和date上添加一个索引,那么只能通过索引扫描来增强一点性能.

标签:mysql,sql,sql-execution-plan,performance
来源: https://codeday.me/bug/20190703/1362962.html