简体   繁体   中英

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.

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

Is there anyother way to write this query?

edit:

TableBB has PRIMARY index on connection between N, X ,Y. and indexes on X, N, M

TableAA has PRIMARY index on X and indexes on 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. My first inclination is to write it with two joins instead of the 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.

Handling the or condition on A is also complicated. You can try having two indexes: A(Y, X, Z) and A(Z, X, Y) and see if they get used. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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