gpt4 book ai didi

MySQL 在 NOT NULL 列中插入具有 NULL 值的记录

转载 作者:可可西里 更新时间:2023-11-01 06:32:13 24 4
gpt4 key购买 nike

为什么第一个 INSERT 会通过 table2。请注意,table2.col_1 不是 NULL。它不会为 col_1 插入 NULL,而是神秘地将 NULL 值转换为空字符串。我正在使用 MySQL 版本 5.5.28。谢谢

mysql> DROP TABLE IF EXISTS table1, table2;

Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS table1 (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
-> col_1 VARCHAR(45) NOT NULL ,
-> col_2 VARCHAR(45) NOT NULL ,
-> PRIMARY KEY (`id`))
-> ENGINE = InnoDB;

Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE table2 LIKE table1;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO table1 (id, col_1, col_2) VALUES (NULL, "xxx","yyy");
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO table2 (id, col_1, col_2) SELECT NULL, NULL, col_2 FROM table1 WHERE id=1;
Query OK, 1 row affected, 1 warning (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 1

mysql> SHOW WARNINGS;
+---------+------+-------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------+
| Warning | 1048 | Column 'col_1' cannot be null |
+---------+------+-------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM table2;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
| 1 | | yyy |
+----+-------+-------+
1 row in set (0.00 sec)

mysql> INSERT INTO table2 (id, col_1, col_2) VALUES( NULL, NULL, "zzz");
ERROR 1048 (23000): Column 'col_1' cannot be null

mysql> SELECT * FROM table2;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
| 1 | | yyy |
+----+-------+-------+
1 row in set (0.00 sec)

最佳答案

您关闭了 MySQL 的 STRICT 模式。打开它,你会得到一个错误。

否则,您可以通过以下方式使用 PDO 测试这些警告:http://php.net/manual/en/pdo.errorinfo.php

关于MySQL 在 NOT NULL 列中插入具有 NULL 值的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15905420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com