MySQL returns 查询时最后插入 IS NULL

MySQL returns last inserted when querying IS NULL

每当我在 INSERT 之后直接用 WHERE id is NULL 执行 SELECT 语句时,我会得到最后插入的行。

我正在使用 MySQL 5.1.73.

直接发生在MySQLshell;这是我的控制台:

mysql> CREATE TABLE testing (
    ->     id int(11) NOT NULL AUTO_INCREMENT,
    ->     name VARCHAR(200),
    ->     PRIMARY KEY (id)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO testing (name) VALUES ('test');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM testing WHERE id IS NULL;
+----+------+
| id | name |
+----+------+
|  1 | test |
+----+------+
1 row in set (0.01 sec)

谁能告诉我这是怎么回事?这是一个错误还是我缺少的设置?

我自己找到了答案。 我的 MySQL 版本(5.1.73,CentOS 6 上的最后一个可用版本)默认设置 sql_auto_is_null,而较新的版本则没有:

╔═════════════════════════════╦══════════════════╦══════════════════╗
║ System Variable (<= 5.5.2)Namesql_auto_is_null ║
║                             ║ Variable Scope   ║ Session          ║
║                             ║ Dynamic Variable ║ Yes              ║
╠═════════════════════════════╬══════════════════╬══════════════════╣
║ System Variable (>= 5.5.3)Namesql_auto_is_null ║
║                             ║ Variable Scope   ║ Global, Session  ║
║                             ║ Dynamic Variable ║ Yes              ║
╠═════════════════════════════╬══════════════════╬══════════════════╣
║ Permitted Values (<= 5.5.2) ║ Type             ║ boolean          ║
║                             ║ Default          ║ 1                ║
╠═════════════════════════════╬══════════════════╬══════════════════╣
║ Permitted Values (>= 5.5.3) ║ Type             ║ boolean          ║
║                             ║ Default          ║ 0                ║
╚═════════════════════════════╩══════════════════╩══════════════════╝

If this variable is set to 1 (the default), then after a statement that successfully inserts an automatically generated AUTO_INCREMENT value, you can find that value by issuing a statement of the following form:

SELECT * FROM <strong><em>tbl_name</em></strong> WHERE <strong><em>auto_col</em></strong> IS NULL

If the statement returns a row, the value returned is the same as if you invoked the LAST_INSERT_ID() function. For details, including the return value after a multiple-row insert, see Section 12.14, “Information Functions”. If no AUTO_INCREMENT value was successfully inserted, the SELECT statement returns no row.

The behavior of retrieving an AUTO_INCREMENT value by using an IS NULL comparison is used by some ODBC programs, such as Access. See Obtaining Auto-Increment Values. This behavior can be disabled by setting sql_auto_is_null to 0.

The default value of sql_auto_is_null is 0 as of MySQL 5.5.3, and 1 for earlier versions.