Mysql

插入 1 個錯誤值 -> 錯誤;插入 2 個錯誤值 -> 警告!

  • June 12, 2018
CREATE TABLE `dummy` (
   `a` TINYINT(4) NOT NULL
) ENGINE=MyISAM;

1 錯誤值

INSERT INTO `dummy` (`a`) VALUES (NULL);
/* SQL Fehler (1048): Column 'a' cannot be null */
/* Nothing is stored! */

2 錯誤值

INSERT INTO `dummy` (`a`) VALUES (NULL), (NULL);
/* Affected rows: 2  Gefundene Zeilen: 0  Warnungen: 2  Dauer von Abfrage: ... sec. */
SHOW WARNINGS LIMIT 5; /* Not sure where this comes from! Maybe HeidiSQL? */
/* Two entries are stored! */

為什麼 MySQL 會在單值查詢中引發錯誤,但在第二個帶有兩個值的查詢中卻沒有?

是否與SHOW WARNINGS LIMIT 5;但這條線來自哪里以及為什麼將錯誤類型從錯誤更改為警告有關?

MySQL V5.6.31

這是 MySQL 的設計方式。根據文件

如果您嘗試將 NULL 儲存到不採用 NULL 值的列中,則單行 INSERT 語句會發生錯誤。對於多行 INSERT 語句或 INSERT INTO … SELECT 語句,MySQL 伺服器儲存列數據類型的隱式預設值。通常,數字類型為 0,字元串類型為空字元串 (’’),日期和時間類型為“零”值。……

我做了一個測試來查看表格的內容(注意我收到了警告!):

mysql> CREATE TABLE `dummy` (
   ->     `a` TINYINT(4) NOT NULL
   -> ) ENGINE=MyISAM;
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO `dummy` (`a`) VALUES (NULL);
ERROR 1048 (23000): Column 'a' cannot be null

mysql> INSERT INTO `dummy` (`a`) VALUES (NULL), (NULL);
Query OK, 2 rows affected, 2 warnings (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 2

mysql> show warnings;
+---------+------+---------------------------+
| Level   | Code | Message                   |
+---------+------+---------------------------+
| Warning | 1048 | Column 'a' cannot be null |
| Warning | 1048 | Column 'a' cannot be null |
+---------+------+---------------------------+
2 rows in set (0.00 sec)

mysql> select * from dummy;
+---+
| a |
+---+
| 0 |
| 0 |
+---+
2 rows in set (0.00 sec)

引用自:https://dba.stackexchange.com/questions/150062