I have a PHP script which runs a MySQL query.
$query = "INSERT INTO table (col1, col2)
VALUES('$val1', '$val2')
ON DUPLICATE KEY UPDATE col2= IF(IS NOT NULL '$val1', 'test', 'col2)";
Here is what I am trying to do: Col1 is the primary key. If there is a duplicate, it checks to see if the insert value for col2 is null. If not, it will update with the value, otherwise the value will stay the same.
This insert fails. When I try to run it manually in sqlyog (inserting actual values in place of variables), I get the following error: Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IS NOT NULL.....'
I have checked the MySQL reference manual for the IS NOT NULL comparison operator (http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_is-not-null), and also for the INSERT ... ON DUPLICATE KEY UPDATE Syntax (http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html) and believe I am using both correctly, but obviously that is not the case.
What am I doing wrong?
For reference, I am using MySQL 5 and the script is running on a RHEL5 server.
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.
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.
Since both primary key and unique columns do not accept duplicate values, they can be used for uniquely identifying a record in the table. This means that, for each value in the primary or unique key column, only one record will be returned.
The syntax IS NOT NULL column
is wrong. Correct: column IS NOT NULL
. I'm not sure what this 'test'
is about. You say that you want to either update the column or keep it as it is.
$query = "INSERT INTO table (col1, col2)
VALUES('$val1', '$val2')
ON DUPLICATE KEY UPDATE col2 = IF('$val2' IS NOT NULL, '$val2', col2)";
which can also be written as:
$query = "INSERT INTO table (col1, col2)
VALUES('$val1', '$val2')
ON DUPLICATE KEY UPDATE
col2 = COALESCE( VALUES(col2), col2)";
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