When using insert... on duplicate key update, what is the syntax to update multiple columns and not update some columns?
i wrote the following query:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"i want this remain the previous value and not change"),(1,2,3)
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=VALUES(text);
how to not change some values and let them remain it's previous value?
Do it with IF:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"ZZZ"),(1,2,3)
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=IF(VALUES(text)="ZZZ", text, VALUES(text));
-for multiple values use IN instead of =:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"ZZZ"),(1,2,"YYY")
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=IF(VALUES(text) IN ("ZZZ", "YYY"), text, VALUES(text));
Related
I want to insert if in the table is not same row with values, but if there is row with the same values I want to only update one that will add +1 to the current value. I have current code, but it doesn't seem to update values in row that exists.
INSERT INTO raport(id, wykonawca, tytul, czas_trwania, powtorzenia)
VALUES('','$wykonawca2','$tytul2','$czas_trwania2', '$powtorzenia2')
ON DUPLICATE KEY UPDATE wykonawca='$wykonawca2', tytul='$tytul2', czas_trwania='$czas_trwania2',
powtorzenia='$powtorzenia2'+1
Ensure your table has a column declared as UNIQUE or PRIMARY KEY and is not an Auto-increment column
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row occurs. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE t1 SET c=c+1 WHERE a=1;
(The effects are not identical for an InnoDB table where a is an auto-increment column. With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.)
MySQL Reference
EDIT :
Your id column is empty you need to pass a value
The actual answer to your initial question as to why the rows do not update is because you are not passing a value for the PRIMARY KEY - this is your AUTO-INCREMENT id column.
Every time you pass :
VALUES('','$wykonawca2','$tytul2','$czas_trwania2', '$powtorzenia2')
this means that your id column is blank, so there is no duplicate just a new row. If you want to have an ON DUPLICATE KEY UPDATE you'll need to pass in the id.
For some more info about ways to handle multiple indexes and DUPLICATE UPDATE check this question out: MySQL behavior of ON DUPLICATE KEY UPDATE for multiple UNIQUE fields
Also, you should read this and action it as soon as possible, you shouldn't be passing variables straight into sql - it's hugely outdated and very unsafe:
How can prepared statements protect from SQL injection attacks?
I have 2 tables as : 'spen_recipe' and 'spen_recipe_type' as shown below
I want to insert the values into spen_recipe and spen_recipe_type simultaneously based on the pk and fk constraints.
Please suggest me the query.
This is what i have tried:
insert into spen_recipe
(`user_id`,`recipe_name`,`recipe_title`,`recipe_type`,`cooking_time`,`preparation_time`,`serving_to`,`recipe_desc`,`recipe_photo`,`created_at`,`modified_at`,`published_at`)
values
('2','recipe2','title2',(select `recipe_type_id` from spen_recipe_type),'20','30','4','desc1','image1','2016-11-05 11:21:43','2016-11-05 11:22:43','2016-11-05 11:21:43');
But need suggestion on how to proceed after select recipe_type_id from spen_recipe_type, cause both the table has null values in the columns, both are empty.
Should spen_recipe_type or spen_recipe be first inserted?
Here is what I want to do. Insert if the unique index (code) doesn't exist in the table already. If it exists then simply update the row.
I can't use primary key because it is Auto Increment ID. Here is the code
$sql="INSERT INTO codes (code,registration,country)
VALUES ('$war','$regi','$country') ON DUPLICATE KEY UPDATE code='$war', registration='$regi', country='$country'";
But it doesn't work because I think it is checking for duplicate primary key. So when I try to insert the row in which the value of column code is same as previous row I get Duplicate entry 'xxx' for key 'code' error. So how to make this work for unique index code ?
Ahmar
ON DUPLICATE KEY UPDATE works with UNIQUE indexes as well as PRIMARY KEY values. Try setting one of the values you are trying to update to be UNIQUE on your database table.
All you have to do is set code to be a unique index. Then, anytime you try to do an insert where code matches it will update instead.
Alter this code as needed
alter table `table` add unique index(`code`);
You are correct, having a primary key on your table will not allow you to insert duplicate key values.
In the past, I have used something like this:
SELECT COUNT(*)
FROM codes
WHERE code = '$war'
Then if the count is > 0, you know there's a duplicate and you do:
UPDATE codes
SET registration = '$regi', country = '$country'
WHERE code = '$war'
Otherwise you do:
INSERT INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
However, if we assume you're using MySQL, you might be able to make use of either INSERT IGNORE or REPLACE.
If you use:
INSERT IGNORE codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
The values will be inserted if the code does not already exist. If the code does exist, no record is inserted and MySQL will silently discard the statement without generating an error.
I think what you probably want is this:
REPLACE INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
REPLACE INTO behaves just like INSERT INTO if the record is new. But if the primary key is duplicated, it will perform an UPDATE instead.
Again, INSERT IGNORE and REPLACE INTO are for MySQL only.
Reference: http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm
I have a following
Table1 : userid, who, share, date :: id is auto increment and primary key
I would like to build a query to check if record exist and insert new record if is empty.
How to build this in a single query and insert multiple records using a single query
data to inser ('a1','a2','a3','a4'), ('b1','b2','b3','b4'), ('c1','c2','c3','c4'), .......
Create UNIQUE index on column that you want to be unique
Use INSERT IGNORE to insert unique data and ignore not unique
You could use REPLACE statemement that works just like INSERT only it doesn't do anything if the row already exists:
REPLACE INTO table ...
http://dev.mysql.com/doc/refman/5.0/en/replace.html
You should take careful look at mysql INSERT INTO documentation.
How to insert "on no exists" is simple. Let's say you want combination of user,who,share to be unique and use latest date. Update your table and create UNIQUE KEY on those fields:
ALTER TABLE Table1 ADD UNIQUE KEY (user, who, share);
Normally inserting the same combination would cause error but using INSERT IGNORE (link above) would silently ignore error:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW());
You may also force key to update on insert:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW())
ON DUPLICATE KEY UPDATE date = VALUES(date);
And inserting multiple values at once, again the first link:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
I'm building a config table with two columns, config_name and config_value. I insert multiple rows in one statement:
INSERT INTO ".$dbPrefix."config (config_name,config_value) VALUES
('domain','$domain'),
('forest_root','$fr_if'),
('userGroup','$userGroup'),
('adminGroup','$adminGroup');
The config_name column is a primary key. How would I change this statement to automatically update the config_value if the config_name already exists?
You could try this syntax:
INSERT INTO table (field) VALUES (value) ON DUPLICATE KEY UPDATE field=value
Docs can be found here.
You're trying to do an upsert, and I think this may help:
http://database-programmer.blogspot.com/2009/06/approaches-to-upsert.html