MySQL 5.1中IN查询不要用到NULL条件

原文见:http://pento.net/2009/04/08/dont-put-a-null-in-the-in-clause-in-51/

如果在 IN 语句中用到 NULL 条件, 会导致全表扫描:

CREATE TABLE foo (
a INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (a)
);

来看看2次查询的区别:

mysql> EXPLAIN * FROM foo WHERE a IN (160000, 160001, 160002)\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: foo
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 3
Extra: Using where
1 row in set (0.06 sec)
mysql> EXPLAIN SELECT * FROM foo WHERE a IN (NULL, 160000, 160001, 160002)\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: foo
type: ALL
possible_keys: PRIMARY
key: NULL
key_len: NULL
ref: NULL
rows: 327680
Extra: Using where
1 row in set (0.00 sec)

 

再加上之前其他同学测试出来的问题:MySQL 5.1 中 Innodb 的事务完整性Bug,看来mysql5.1还是不太靠谱啊,如果不是迫不得已,还是少用吧 :)

回复

此内容将保密,不会被其他人看见。
  • 允许的 HTML 标签: <a> <b> <address> <blockquote> <br> <caption> <center> <code> <dd> <del> <div> <dl> <dt> <em> <font> <h2> <h3> <h4> <h5> <h6> <hr> <i> <img> <li> <ol> <p> <pre> <span> <strong> <sub> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <u> <ul> <tr>
  • 行和段被自动切分。
  • 网页地址和电子邮件地址将会被自动转换为链接。

更多格式化选项信息

随机验证
本功能用于防止垃圾信息
在输入框中输入图片上的字符(注意大小写)