我有下一个代码块,它的执行时间不超过 3 秒。
`CREATE TEMPORARY TABLE tmp
SELECT
MAX(date) as mdate
FROM table1
WHERE
date between "2017-03-13"
and "2018-03-13"
and client_id = "something"
and field_id IN ("123","1234","12345")
GROUP BY DATE_FORMAT(date,'%x_%v');
SELECT
SUM(value),
DATE_FORMAT(date,'%x_%v') as date
FROM
table1, tmp t
WHERE
date = t.mdate
and client_id = "something"
and field_id IN ("123","1234","12345")
GROUP BY date;
DROP TABLE tmp;`
但是当我尝试在一个查询中执行它时,它会在大约 1 分 4.36 秒内执行。
SELECT
SUM(value),
mdates.grouping_date
FROM
(
SELECT
MAX(date) as mdate,
DATE_FORMAT(a.date,'%x_%v') as grouping_date
FROM table1
WHERE
date between "2017-03-13"
and "2018-03-13"
and client_id = "something"
and field_id IN ("123","1234","12345")
GROUP BY grouping_date
) mdates, table1 a
WHERE
a.date = mdates.mdate
and a.client_id = "something"
and a.field_id IN ("123","1234","12345")
GROUP BY mdates.grouping_date;
我应该怎么做才能让它作为第一个 block 运行得更快?
我在想也许我可以使用复合索引,但我已经尝试过这个但没有帮助。
create index my_idx on table1(date,field_id,client_id);
更新:
解决我的问题的方法是创建几个索引。
create index index1 on table1(client_id,field_id,date)
create index index2 on table2(date,value)
现在它的运行速度与使用临时表的第一个查询一样快。
但我不得不稍微更改一下查询。
SELECT
SUM(value),
DATE_FORMAT(date,'%x_%v') as date
FROM
table1 a FORCE INDEX(index2)
WHERE
a.date in (
SELECT
MAX(date)
FROM
table1 FORCE INDEX(index1)
WHERE
client_id = "something"
and repo_id IN ("123","1234","12345")
and date >= "2018-02-11"
and date < "2018-03-13"
GROUP BY DATE_FORMAT(date,'%v_%x')
)
GROUP BY date';
最佳答案
对于您的查询,我会将复合索引创建为:
create index my_idx on table1(client_id, field_id, date);
WHERE
条件 首先 在索引中,然后是其他条件。用于相等条件的列应该放在第一位。
关于mysql - 查询相当于临时表mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49542813/