简体   繁体   English

您如何优化以下mysql查询

[英]How would you optimize the following mysql query

Can anybody help me in optimizing this mysql query in php, it takes up to 100 sec. 任何人都可以帮助我优化php中的mysql查询,它最多需要100秒。

SELECT DISTINCT
A.X,
A.Y,
A.Z,

FROM TableAA AS A 

INNER JOIN( TableBB AS B) 

ON(A.X = B.X) OR (A.X = B.M)

WHERE B.N = '$input' OR
  A.Y = '$input' OR
  A.Z = '$input'

TableAA has 1 million enteries TableBB has 9 million enteries TableAA拥有100万个肠子TableBB拥有900万个肠子

Is there anyother way to write this query? 还有其他写此查询的方式吗?

edit: 编辑:

TableBB has PRIMARY index on connection between N, X ,Y. TableBB在N,X,Y之间的连接上具有主索引。 and indexes on X, N, M 以及在X,N,M上的索引

TableAA has PRIMARY index on X and indexes on Y, Z TableAA在X上具有PRIMARY索引,在Y,Z上具有索引

Your query (formatted in a way that I can better understand it) is: 您的查询(以我可以更好地理解它的格式)是:

SELECT DISTINCT A.X, A.Y, A.Z
FROM TableAA A INNER JOIN
     TableBB B
     ON A.X = B.X OR A.X = B.M
WHERE B.N = '$input' OR A.Y = '$input' OR A.Z = '$input';

This is complex for optimization because of all the or clauses. 由于所有or子句,优化起来很复杂。 My first inclination is to write it with two joins instead of the or : 我的第一个倾向是使用两个联接而不是or来编写它:

SELECT DISTINCT A.X, A.Y, A.Z
FROM TableAA A left outer JOIN
     TableBB B
     ON A.X = B.X and B.N = '$input' left outer join
     TableBB b2
     on A.X = B2.M and B2.N = '$input'
WHERE (B.N is not null or B2.N is not null) and (A.Y = '$input' OR A.Z = '$input')

This is more complicated, but you can now add indexes on B(N, X) and B(N, M) to facilitate the processing. 这更加复杂,但是您现在可以在B(N, X)B(N, M)上添加索引以方便处理。

Handling the or condition on A is also complicated. 处理Aor条件也很复杂。 You can try having two indexes: A(Y, X, Z) and A(Z, X, Y) and see if they get used. 您可以尝试使用两个索引: A(Y, X, Z)A(Z, X, Y)并查看它们是否被使用。 Otherwise, you can split this into two queries: 否则,您可以将其分为两个查询:

(SELECT A.X, A.Y, A.Z
 FROM TableAA A left outer JOIN
      TableBB B
      ON A.X = B.X and B.N = '$input' left outer join
      TableBB b2
      on A.X = B2.M and B2.N = '$input'
 WHERE (B.N is not null or B2.N is not null) and A.Y = '$input'
)
union
(SELECT A.X, A.Y, A.Z
 FROM TableAA A left outer JOIN
      TableBB B
      ON A.X = B.X and B.N = '$input' left outer join
      TableBB b2
      on A.X = B2.M and B2.N = '$input'
 WHERE (B.N is not null or B2.N is not null) and A.Z = '$input'
)

This version should use the indexes mentioned above. 此版本应使用上述索引。 Of course, you need to check the explain plans to see if this is really the case. 当然,您需要检查explain计划以查看是否确实如此。 But this might help with optimization. 但这可能有助于优化。

If there is any way to simplify the conditions so they are and rather than or , then such optimization is easier. 如果有任何方法可以简化条件,则条件为and而不是or ,则这种优化会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM