简体   繁体   中英

How would you optimize this MySQL query

Can anybody help me in optimizing this query,

SELECT(X1,      
    X2   
FROM TABLEAA   
 WHERE   
        Y IN (SELECT Y FROM TABLEBB WHERE Z=SELECTED)   
    AND Y  IN  (SELECT Y  FROM TABLECC  WHERE ZZ=SELECTED)    
)

WHERE AS

TABLEAA : 1 million enteries    
TABLEBB : 22 million enteries    
TABLECC : 1.2 million enteries  

it works but take too much time, almost 30 sec

Is there any other way to right this?

edit: the Z and ZZ are totally two different column

Instead of using subqueries, join TABLEBB and TABLECC to TABLEAA, and check for ZZ=SLECTED in your WHERE clause, for both joined tables.

Make sure the columns that participate in the outer joins are indexed.

I would use JOINs :

SELECT DISTINCT
    A.X1,      
    A.X2   
FROM TABLEAA A
   JOIN TABLEBB B ON A.Y = B.Y AND B.Z='SELECTED'
   JOIN TABLECC C ON A.Y = C.Y AND C.Z='SELECTED'

Also, make sure you have the appropriate indexes on AY, BY and CY You may find a better performance by adding indexes on you Z columns -- this depends on your table structure and several other factors.

Indexes...

  • Add an index to Z in TABLEBB
  • Add an index to ZZ in TABLECC
  • Add an index to Y in TABLEAA
SELECT X1, X2 FROM TABLEAA 
JOIN TABLEBB ON Y = Y JOIN TABLECC ON Y = Y 
WHERE TABLEBB.Z = SLECTED && TABLECC.ZZ = SLECTED

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