希望优化此查询
SELECT gwt.z, gwt.csp, gwt.status, gwt.cd, gwt.disp, gwt.5d, gwt.6d, gwt.si, gwt.siad, gwt.prbd,
CONCAT(gwt.1, gwt.2, gwt.3, gwt.4, gwt.5, gwt.6, gwt.7, gwt.8, gwt.9),
group_concat(gws.res order by line_no), gwt.scm, gm.me, gwt.p, gwt.scd
from gwt
left outer join gws on gwt.csp = gws.csp
left join gm on gwt.scm = gm.mid
where gwt.zone = 1
and (status like '1%' or status like '2%' or status like '3%' or
status like '4%' or status like '5%' or status like '6%')
group by gwt.csp
使用 EXPLAIN,gwt 有 4110 行,gws 有 920k 行,gm 有 2800 行。
当我只查询 1% 之类的状态时,查询加载得很好,但由于我添加了要显示的其他状态,因此出现超时错误。
最佳答案
我建议如下。
确保每个表都有一个类似于其主键的索引:
- gwt.csp
- gm.mid
对于gwt,在(zone, status)上创建另一个索引并将连接条件更改为:
gwt.zone = 1 and status >= '1' and status < '7'
这相当于您的列表,但它将允许执行引擎使用索引。
这可能足以修复查询。最后,您可以在 gws.csp 上放置一个索引,看看是否可以加快速度。
“csp”是一对一的关系吗?如果不是这样,则创建巨大结果集的查询可能会出现问题。
关于mysql - 使用 3 个表进行查询优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12041638/