简体   繁体   中英

Long SQL query - how to optimize?

I have an sql query that run about 24 hours. I would like to know if there is a way to optimize it.

The Query is:

update r, t  set r.a1 = t.a2, r.b1 = t.b1  where r.c = t.c and r.d1 = t.d2 and r.e1 = t.e2 and r.f1 = t.f2;

Table r have ~2,000,000 rows and defined as:

Field  Type      Collation  Null  Key  Default Extra         
-----  --------  ---------  ----  ---  ------  --------------

id     int(11)   (NULL)     NO    PRI  (NULL)  auto_increment

a1     blob      (NULL)     YES        (NULL)                

e1     tinyblob  (NULL)     YES   MUL  (NULL)                

f1     int(11)   (NULL)     YES   MUL  (NULL)                

c      int(11)   (NULL)     YES   MUL  (NULL)                

b1     int(11)   (NULL)     YES   MUL  (NULL)                

d1     int(11)   (NULL)     YES   MUL  (NULL)                

Table t have ~1,200,000 rows and defined as:

Field  Type      Collation  Null  Key     Default  Extra         

-----  --------  ---------  ----  ------  -------  --------------

c      int(11)   (NULL)     NO    MUL     0                      

d2     int(11)   (NULL)     NO    MUL     0                      

e2     tinyblob  (NULL)     YES   MUL     (NULL)                 

f2     int(2)    (NULL)     NO    MUL     (NULL)                 

a2     blob      (NULL)     YES           (NULL)                 

b1     int(11)   (NULL)     YES           0                      

id     int(11)   (NULL)     NO    PRI     (NULL)   auto_increment

I would like to know if there is a way to optimize the query?

Thanks!

Your index key should be ordered the same as your where statement. r table key:

c,d1,e1,f1

and t table key:

c,d2,e2,f2

Do you need a key in r table on column b1 ?

Your structure seems quite OK. 2M rows in not that much. Your rows may be large (with the blobs ), but the comparison you do are only on integer values. It should be faster.

Try to run ANALYZE , OPTIMIZE , CHECK , REPAIR commands on your tables to make sure your indexes are correctly constructed.

Once this is done, you should try investigate deeper in the system. What is slowing down the query ? It can be :

Use monitoring to have data about your sql cache, memory usage etc. It will help you diagnose the issue.

Try this

update r left join t on r.c = t.c and r.d1 = t.d2 and r.e1 = t.e2 and r.f1 = t.f2 set r.a1 = t.a2, r.b1 = t.b1

Also Do some changes

  • make c,d1,e1 column indexed in table r

  • make c,d2,e2 column indexed in table t

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