MySQL 多個in 條件需要注意的地方

MySQL當對一列進行操作時,如果in的條件太多,即使這列上有索引,也是導致執行計劃不走索引
因爲搜索的記錄數太多,MySQL會認爲全表掃描可能會更快

對一個表進行刪除操作,如果這個列上沒有索引,或者執行計劃沒有走搜索,會導致刪除鎖住全部的列

sesson1

mysql> show indexes from city1;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| city1 |          0 | PRIMARY  |            1 | ID          | A         |        3764 |     NULL | NULL   |      | BTREE      |         |               |
| city1 |          1 | idx_code |            1 | CountryCode | A         |         232 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec)

mysql> alter table city1 drop index idx_code;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 
mysql> 
mysql> select * from city1 limit 10;
+----+----------------+-------------+---------------+------------+
| ID | Name           | CountryCode | District      | Population |
+----+----------------+-------------+---------------+------------+
|  1 | Kabul          | AFG         | Kabol         |    1780000 |
|  2 | Qandahar       | AFG         | Qandahar      |     237500 |
|  3 | Herat          | AFG         | Herat         |     186800 |
|  4 | Mazar-e-Sharif | AFG         | Balkh         |     127800 |
|  5 | Amsterdam      | NLD         | Noord-Holland |     731200 |
|  6 | Rotterdam      | NLD         | Zuid-Holland  |     593321 |
|  7 | Haag           | NLD         | Zuid-Holland  |     440900 |
|  8 | Utrecht        | NLD         | Utrecht       |     234323 |
|  9 | Eindhoven      | NLD         | Noord-Brabant |     201843 |
| 10 | Tilburg        | NLD         | Noord-Brabant |     193238 |
+----+----------------+-------------+---------------+------------+
10 rows in set (0.00 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> update city1 set name='aaa' where CountryCode='AFG';
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4  Changed: 4  Warnings: 0

session2

mysql> begin
    -> ;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from city1  where CountryCode='NLD';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

如果添加上索引,則上面的執行沒有問題,不會有阻塞。

alter table city1 add index idx_code (CountryCode);

MySQL強制走索引

select * from ws_shop a force index(create_time)
where date(create_time-interval 6 hour) > '2016-10-01 06:00:00';

force index 只支持select ,不支持delete

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章