如何使用MyISAM表加速对MySQL使用两次相同表的查询?

时间:2016-07-19 09:07:02

标签: mysql select myisam

我使用类似下面的查询,使用两次相同的表utdat来恢复数据。

将2表连接在一起的关键是tableA.utprog = tableB.utprog。

SELECT tableA.upd, tableB.utdata  FROM utdat as tableA, utdat AS tableB 
WHERE tableA.uttdat = 'I' AND tableA.utctip = '01' AND   
substring(tableA.utreco, 1, 1) = '3' 
AND tableB.uttdat = 'I' AND tableB.utctip = '01' AND 
substring(tableB.utreco, 1, 1) = '1' 
AND tableA.utprog = tableB.utprog AND TRIM(substr(tableB.utreco, 65, 
12)) = '20000190';

有一种方法可以加快MyISAM db上的查询速度吗?

1 个答案:

答案 0 :(得分:2)

WHERE子句中使用的3列上创建多列索引:

ALTER TABLE utdat ADD INDEX (uttdat, utctip, itreco);

SUBSTRING(tableA.utreco, 1, 1) = 3更改为tableA.utreco LIKE '3%', as MySQL knows how to optimize prefix matching in a LIKE expression, but it may not realize that SUBSTR`正在提取前缀。

它不会影响性能,但您还应该学习ANSI JOIN语法。

SELECT tableA.upd, tableB.utdata  
FROM utdat as tableA
JOIN utdat AS tableB ON tableA.utprog = tableB.utprog
WHERE tableA.uttdat = 'I' AND tableA.utctip = '01' AND tableA.utreco LIKE '3%' 
AND tableB.uttdat = 'I' AND tableB.utctip = '01' AND tableB.utreco LIKE '1%' 
AND TRIM(substr(tableB.utreco, 65, 12)) = '20000190';