(1)優(yōu)化前
在白朗等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供網(wǎng)站制作、成都做網(wǎng)站 網(wǎng)站設(shè)計制作按需策劃設(shè)計,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),全網(wǎng)營銷推廣,成都外貿(mào)網(wǎng)站制作,白朗網(wǎng)站建設(shè)費用合理。
如下一條SQL,把從1985-05-21入職前的員工薪資都增加500,執(zhí)行約20.70 s,
從執(zhí)行計劃中可以看出對表salaries進(jìn)行的是索引全掃描,掃描行數(shù)約260W行。
MySQL> update salaries set salary=salary+500 where emp_no in (select emp_no from employees where hire_date<='1985-05-21'); Query OK, 151583 rows affected (20.70 sec) Rows matched: 151583 Changed: 151583 Warnings: 0 mysql> desc update salaries set salary=salary+500 where emp_no in (select emp_no from employees where hire_date<='1985-05-21'); +----+--------------------+-----------+------------+-----------------+---------------+---------+---------+------+---------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+--------------------+-----------+------------+-----------------+---------------+---------+---------+------+---------+----------+-------------+ | 1 | UPDATE | salaries | NULL | index | NULL | PRIMARY | 7 | NULL | 2674458 | 100.00 | Using where | | 2 | DEPENDENT SUBQUERY | employees | NULL | unique_subquery | PRIMARY | PRIMARY | 4 | func | 1 | 33.33 | Using where | +----+--------------------+-----------+------------+-----------------+---------------+---------+---------+------+---------+----------+-------------+ 2 rows in set, 1 warning (0.00 sec)
(2)優(yōu)化后
把in改寫成join后,雖然對employees是全表掃描,但是掃描行數(shù)近29W行,大大減少,所以SQL執(zhí)行時間可以縮減到7.26s.
mysql> update salaries s join (select distinct e.emp_no from employees e where e.hire_date<='1985-05-21') e on s.emp_no=e.emp_no -> set s.salary=salary+500; Query OK, 151583 rows affected (7.26 sec) Rows matched: 151583 Changed: 151583 Warnings: 0 mysql> desc update salaries s join (select distinct e.emp_no from employees e where e.hire_date<='1985-05-21') e on s.emp_no=e.emp_no -> set s.salary=salary+500; +----+-------------+------------+------------+------+----------------+---------+---------+----------+--------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+------------+------------+------+----------------+---------+---------+----------+--------+----------+-------------+ | 1 | PRIMARY || NULL | ALL | NULL | NULL | NULL | NULL | 99827 | 100.00 | NULL | | 1 | UPDATE | s | NULL | ref | PRIMARY,emp_no | PRIMARY | 4 | e.emp_no | 10 | 100.00 | NULL | | 2 | DERIVED | e | NULL | ALL | PRIMARY | NULL | NULL | NULL | 299512 | 33.33 | Using where | +----+-------------+------------+------------+------+----------------+---------+---------+----------+--------+----------+-------------+ 3 rows in set, 1 warning (0.00 sec)