Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL default value error with ON DUPLICATE KEY UPDATE

Tags:

mysql

Why am I getting this error? Did something change with MySQL versions which would cause this (which worked at one point) to now fail? The INSERT INTO does not specify the user_id value which would be required if an insert was done, but since id 1 already exists, this should become an UPDATE and be valid.

mysql> select * from article;
+----+---------+---------------------+-----------+-----------+
| id | user_id | published_at        | title     | content   |
+----+---------+---------------------+-----------+-----------+
|  1 |       1 | 2011-12-10 12:10:00 | article 1 | content 1 |
|  2 |       2 | 2011-12-20 16:20:00 | article 2 | content 2 |
|  3 |       1 | 2012-01-04 22:00:00 | article 3 | content 3 |
+----+---------+---------------------+-----------+-----------+
3 rows in set (0.00 sec)

mysql> desc article;
+--------------+------------------+------+-----+-------------------+----------------+
| Field        | Type             | Null | Key | Default           | Extra          |
+--------------+------------------+------+-----+-------------------+----------------+
| id           | int(11) unsigned | NO   | PRI | NULL              | auto_increment |
| user_id      | int(11) unsigned | NO   | MUL | NULL              |                |
| published_at | datetime         | NO   |     | CURRENT_TIMESTAMP |                |
| title        | varchar(100)     | NO   |     | NULL              |                |
| content      | text             | NO   |     | NULL              |                |
+--------------+------------------+------+-----+-------------------+----------------+
5 rows in set (0.01 sec)

mysql> INSERT INTO article (id)
    -> VALUES (1)
    -> ON DUPLICATE KEY UPDATE title = 'article 1b', content = 'content 1b';
ERROR 1364 (HY000): Field 'user_id' doesn't have a default value

MySQL version 5.6.12.

like image 858
CXJ Avatar asked Jul 05 '13 00:07

CXJ


1 Answers

You're getting error because

  1. The user_id column is defined as NOT NULL
  2. The user_id column doesn't have a default value specified
  3. You don't specify its value in your query either

PS: the question is irrelevant to the ON DUPLICATE KEY UPDATE clause - it would be the same error if you didn't use it as well.

PPS: regardless of if the ON DUPLICATE KEY UPDATE triggered - your insert should satisfy all the constraints

like image 98
zerkms Avatar answered Nov 03 '22 00:11

zerkms