我想得到一个项目#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
答案 0 :(得分:1)
根据看到解释结果invoice_header
不能使用任何多重索引。
您可以在invo_no
表格上的字段invoice_header
上创建索引。
答案 1 :(得分:1)
遵循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上添加一个索引,那么只能通过索引扫描来增强一点性能。
答案 2 :(得分:0)
尝试在某些列上创建一些索引:invo_no,loc_id,item_id,date。
根据您的说明,您的查询正在扫描invoice_header中的所有行。索引进行连接的列... invo_no,loc_id