ORDER BY使MySQL查询运行速度非常慢

时间:2011-12-04 17:44:59

标签: mysql sql sql-order-by

我有以下MySQL查询:

SELECT 
   table1.*, table2.*    
FROM 
   `Table1` AS table1, 
   `Table2` AS table2, 
   `Table3` 
WHERE 
   table1.col1 = table2.col1 AND
   table1.col1 = Table3.col1 AND  
   table1.col1 != '0' AND 
   table1.col1 NOT IN (1,2) 
   table1.col2 LIKE 'A' AND 
   (table1.col3 LIKE 'A' OR table1.col3 LIKE 'B') AND 
   Table3.col4 = 0 AND 
   Table3.col5 = 0 AND 
   Table3.col6 = 0 
ORDER BY 
   table1.col10 ASC 
LIMIT 0, 5

没有ORDER BY语句,它会在0.002秒内执行。

使用ORDER BY语句,它会在2秒内执行。

我看到this answer似乎适用于OP,但当我在我的网上尝试时,我遇到Duplicate column name 'col1'错误。

关于如何使用ORDER BY加快速度的任何想法?

修改

根据要求,以下是我根据上面的链接尝试的修改后的查询,该查询给出了Duplicate column name 'col1'错误:

SELECT * FROM (
    SELECT 
       table1.*, table2.*    
    FROM 
       `Table1` AS table1, 
       `Table2` AS table2, 
       `Table3` 
    WHERE 
       table1.col1 = table2.col1 AND
       table1.col1 = Table3.col1 AND  
       table1.col1 != '0' AND 
       table1.col1 NOT IN (1,2) 
       table1.col2 LIKE 'A' AND 
       (table1.col3 LIKE 'A' OR table1.col3 LIKE 'B') AND 
       Table3.col4 = 0 AND 
       Table3.col5 = 0 AND 
       Table3.col6 = 0 
) AS t1
ORDER BY 
   table1.col10 ASC 
LIMIT 0, 5

显然,这应该确保ORDER BY仅在确定最终结果集后才能完成。

2 个答案:

答案 0 :(得分:0)

尝试在table1col10添加索引。

答案 1 :(得分:0)

您还可以探索使用临时表

SELECT
   table1.*, table2.* INTO #temp
FROM 
   `Table1` AS table1, 
   `Table2` AS table2, 
   `Table3` 
WHERE 
   table1.col1 = table2.col1 AND
   table1.col1 = Table3.col1 AND  
   table1.col1 != '0' AND 
   table1.col1 NOT IN (1,2) 
   table1.col2 LIKE 'A' AND 
   (table1.col3 LIKE 'A' OR table1.col3 LIKE 'B') AND 
   Table3.col4 = 0 AND 
   Table3.col5 = 0 AND 
   Table3.col6 = 0 

SELECT * FROM #temp  
ORDER BY col10 ASC 
LIMIT 0, 5
相关问题