1

Common query for both create and update contact. While doing an updation for a field:- An exception occurred while executing

INSERT INTO contact_table 
SET id = '1234',
is_stealth_mode = 1 
ON DUPLICATE KEY UPDATE 
id = LAST_INSERT_ID( id ),
is_stealth_mode = VALUES(is_stealth_mode)

General error: 1364 Field 'club_id' doesn't have a default value

contact_table has a field club_id which has default value none and not nullable

strict mode is enabled

contact_table already has value id = '1234' and 'club_id' = 123

Neethu George
  • 587
  • 5
  • 8

3 Answers3

1

You need to specify what each column should update to in the ON DUPLICATE KEY UPDATE clause

id = LAST_INSERT_ID( id ),
is_stealth_mode = VALUES(is_stealth_mode),
club_id = club_id

to keep the existing value

Or

id = LAST_INSERT_ID( id ),
is_stealth_mode = VALUES(is_stealth_mode),
club_id = VALUES(club_id)

if you want to update the field value

andrew
  • 9,313
  • 7
  • 30
  • 61
  • I want to keep existing value (quite obvious). Suggested query does not work. Only if you put `club_id` in values with some dummy value, then it's ok, but it's so dirty hack – The Godfather Jul 08 '19 at 21:38
  • @TheGodfather did the first of the above 2 queries not work ? i would think that `club_id = club_id` should keep the existing value ? – andrew Jul 10 '19 at 03:58
0

"contact_table has a field club_id which has default value none and not nullable"

From your above statement, is it means that club_id doesn't have default value or it's default value is 'NONE'. It seems to be club_id is not nullable and you should provide that value in the query.

Ram
  • 221
  • 1
  • 2
  • 7
0

The idea here is that just normal INSERT is being executed first, and since your DB has NOT NULL constraint, it complains. So ON DUPLICATE part doesn't really matter (see also https://stackoverflow.com/a/17479690/1657819).

One of possible options - put dummy value for club_id field, but not use it in UPDATE part.

But of course, if no such id exists, then the entry with dummy data will be created.

    INSERT INTO contact_table 
      SET id = '1234',
      is_stealth_mode = 1 ,
      club_id="dummy"  <---- Note dummy value which is not used in ON DUPLICATE part
    ON DUPLICATE KEY UPDATE 
      id = LAST_INSERT_ID( id ),
      is_stealth_mode = VALUES(is_stealth_mode)

As an alternative, you can change the schema to allow NULL values:

ALTER TABLE contact_table
    CHANGE COLUMN `club_id` `club_id` INT NULL <...>
The Godfather
  • 4,235
  • 4
  • 39
  • 61