Mysql查询优化建议
我想优化此查询以加速结果。目前,此查询在windows 7 32位操作系统、4 GB RAM中运行约4到5分钟 交易记录表中的记录计数\u销售额:400000 产品类别中的记录计数:200000 这是我的问题Mysql查询优化建议,mysql,sql,Mysql,Sql,我想优化此查询以加速结果。目前,此查询在windows 7 32位操作系统、4 GB RAM中运行约4到5分钟 交易记录表中的记录计数\u销售额:400000 产品类别中的记录计数:200000 这是我的问题 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
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.2279秒。。多谢各位
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;