MySQL INSERT without having to specify every non-default field (#1067 - Invalid default value for 'table')

筅森魡賤 提交于 2019-12-05 16:58:23

One of your servers is running in strict mode by default and the other not. If a server runs in strict mode (or you set it in your connection) and you try to insert a NULL value into a column defined as NOT NULL you will get #1364 error. Without strict mode your NULL value will be replaced with empty string or 0.

Example:

CREATE TABLE `test_tbl` (
 `id` int(11) NOT NULL,
 `someint` int(11) NOT NULL,
 `sometext` varchar(255) NOT NULL,
 `somedate` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

SET sql_mode = '';
INSERT INTO test_tbl(id) VALUES(1);
SELECT * FROM test_tbl;
+----+---------+----------+---------------------+
| id | someint | sometext | somedate            |
+----+---------+----------+---------------------+
|  1 |       0 |          | 0000-00-00 00:00:00 |
+----+---------+----------+---------------------+
SET sql_mode = 'STRICT_ALL_TABLES';
INSERT INTO test_tbl(id) VALUES(2);
#1364 - Field 'someint' doesn't have a default value 
INSERT INTO table SET value_a='a', value_b='b'

Will perform the following query:

On the following table

TABLE `table`
    a varchar
    b varchar
    c varchar NOT NULL -- column is listed as NOT NULL !

And you are doing the following query on it

INSERT INTO `table` (a,b,c) VALUES ('a', 'b', null)

So you are trying to insert a null value in a not null column that does not have a default value listed. This is why you are getting the error.

But why am I getting this error on server B and not on server A

Possible reasons are:

  1. The create table statements are not the same: do a show create table table1 on each server and compare the output carefully.
  2. There is a before insert trigger present on server A but not on server B (or visa versa) that is changing the input you are inserting. do a show triggers in databasex on each server and compare the output.
  3. The table on server A is using a different engine from server B. This will show up in the output of show create table as the last line e.g. ENGINE=MyISAM

See: http://dev.mysql.com/doc/refman/5.0/en/show-triggers.html
http://dev.mysql.com/doc/refman/5.0/en/show-create-table.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!