我想优化此查询以加快结果。目前,此查询在Windows 7 32位操作系统,4 GB RAM中运行大约4到5分钟。
表transaction_sales中的记录计数:400,000 product_category中的记录计数:200,000 这是我的查询
SELECT c.category_name,
ROUND(sum(CASE WHEN t.business_date = '2017-12-24' THEN t.sales ELSE 0 END),0) today_sales,
sum(CASE WHEN t.business_date = '2017-12-24' THEN t.qty ELSE 0 END) today_qty,
COUNT(DISTINCT(CASE WHEN t.business_date = '2017-12-24' THEN t.tran_id END )) AS today_transactions,
round(sum(t.sales),0)tilldate_sales,
sum(t.qty)tilldate_qty,
count(distinct t.tran_id)tilldate_transactions
FROM transaction_sales t join product_category c on c.product_code=t.product_code
group by c.category_name;
这些是我的索引详细信息表,
CREATE TABLE product_category (
product_code varchar(25) NOT NULL,
category_name varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE transaction_sales (
id int(11) NOT NULL,
business_unit_id int(11) NOT NULL,
business_date date NOT NULL,
tran_id varchar(10) NOT NULL,
product_code varchar(25) NOT NULL,
sales float NOT NULL,
qty int(11) NOT NULL,
last_update datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE product_category
ADD PRIMARY KEY (product_code);
ALTER TABLE transaction_sales
ADD PRIMARY KEY (id),
ADD UNIQUE KEY business_unit_id (business_unit_id,business_date,tran_id,product_code),
ADD KEY business_date (business_date),
ADD KEY product_code (product_code);
ALTER TABLE transaction_sales
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
请建议如何加快结果。
答案 0 :(得分:3)
CASE条件将成为减缓其速度的主要因素 - 每条记录三次评估。如果您可以通过运行两个查询而不是一个查询来管理:一个用于显示特定日期的数字(原始查询中的第一个组):
SELECT c.category_name,
ROUND(sum(t.sales)) today_sales,
sum(t.qty) today_qty,
COUNT(DISTINCT(t.tran_id)) AS today_transactions
FROM transaction_sales t join product_category c on c.product_code=t.product_code WHERE t.business_date = '2017-12-24'
group by c.category_name;
第二个给你整张表的数字(原始查询中的第二组三个字段):
SELECT c.category_name,
ROUND(sum(t.sales)) today_sales,
sum(t.qty) today_qty,
COUNT(DISTINCT(t.tran_id)) AS today_transactions
FROM transaction_sales t join product_category c on c.product_code=t.product_code
group by c.category_name;
这应该会大大加快速度。我已经使用您的表定义检查了测试构建中的查询在语法上是否正确,但显然没有数据 - 尽管它在空数据集上运行得非常快!!