2011-07-01 42 views
0

我有一个查询,其中有多个表使用distincct - 左连接 - order by - limit子句连接。MySQL查询优化与表的数量加入和按限制条款排序

查询看起来是这样的: -

Select DISTINCT a.col1, b.col2, c.col3, d.col4, e.col5, f.col6, g.col7, h.col8, 
i.col9, j.col10 
From test_a a 
left join test_b b on a.col1 = b.col2 
left join test_c c on c.col1 = d.col2 
left join test_d d on d.col1 = c.col2 
left join test_e e on e.col1 = d.col2 
left join test_f f on f.col1 = e.col2 
left join test_g g on g.col1 = f.col2 
left join test_h h on h.col1 = a.col1 
left join test_i i on i.col1 = f.col2 
left join test_j j on j.col1 = i.col2 
Where a.col2 = 'Y' 
and c.col4 = 1 
Order by h.col5 desc 
limit 50; 

所有列中使用的在coditions有指标就可以了。并解释这个查询的输出结果集,在那里我可以看到它使用所有索引正确,它从所有表中扫描的总行数是18000.

我在这个查询中想知道的是: - 这个查询运行在几秒钟内我运行它没有条款的顺序。像这样: -

Select DISTINCT a.col1, b.col2, c.col3, d.col4, e.col5, f.col6, g.col7, h.col8, 
i.col9, j.col10 
From test_a a 
left join test_b b on a.col1 = b.col2 
left join test_c c on c.col1 = d.col2 
left join test_d d on d.col1 = c.col2 
left join test_e e on e.col1 = d.col2 
left join test_f f on f.col1 = e.col2 
left join test_g g on g.col1 = f.col2 
left join test_h h on h.col1 = a.col1 
left join test_i i on i.col1 = f.col2 
left join test_j j on j.col1 = i.col2 
Where a.col2 = 'Y' 
and c.col4 = 1 
limit 50; 

如果我用order by子句运行它,则需要30-40秒执行。

我尝试使用mysql:- USE INDEX FOR ORDER BY (idx_h_col5) 提供的索引提示功能,但我在执行此查询时出现语法错误。错误消息说不正确的语法附近

我有一个组合索引在按顺序使用的子句。我也尝试在这个列上创建一个索引,但没有任何真正的工作。

任何输入将是很大的帮助。

在此先感谢。

问候, 玛纳斯

+0

多少行做的表有一个简单的指标?如果您提供了有序查询的执行计划,这将有所帮助。表的结构(PK,FKs)和现有的索引。 –

+0

大多数表格都有百万行以上的行。我会得到解释的输出并把它放在这里。谢谢 –

回答

1

的MySQL可以使用按键进行排序,而不是获取数据后的结果排序,但只有满足几个条件。 你可以在这里看到这些条件的列表:http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

在你的情况,我认为多个JOIN阻止快速排序。其中所提到的案件中,MySQL不能使用索引来排序是:

您在ORDER BY联接许多表和 列不是所有从第一非恒定表 即 是用于检索行。 (这是EXPLAIN输出 第一表 没有一个const连接类型。)

我不知道是否有办法解决它。它取决于表结构和实际查询。

要获得更多帮助,请尝试张贴有序查询的说明输出。

0

我第一次尝试在添加复合指数:

Table a 
    (col2, col1) 

Table b 
    (col4, col1) 

Table h 
    (col5)