I have the following structure
user_id int(11)
right int(11)
group_id int(11)
value tinyint(1)
And 3 queries
INSERT INTO user_rights (`user_id`,`right`,`group_id`,`value`)
VALUES ( '42', '160', '1', '1' );
INSERT INTO user_rights ('user_id','right','group_id','value')
VALUES ( '42', '160', '1', '1' );
INSERT INTO user_rights (user_id,right,group_id,value)
VALUES ( '42', '160', '1', '1' );
Explain me WHYYYY only the first works????
I have all my life used the third one!
INSERT ... ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.
The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.
Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
By definition, atomicity requires that each transaction is an all or nothing. So yes it is atomic in the sense that if the data that you are trying to insert will cause a duplicate in the primary key or in the unique index, the statement will instead perform an update and not error out.
RIGHT
is a mySQL reserved word. It will work only when wrapped in backticks.
When you're not using reserved words, it will work without the backticks, as well.
The second way will never work because quotes are used to quote strings, but never database, table or column identifiers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With