I've seen the following (using the VALUES option):
$query = "INSERT INTO $table (column-1, column-2, column-3) VALUES ('value-1', 'value-2', 'value-3') ON DUPLICATE KEY UPDATE SET column1 = value1, column2 = value2, column3 = value3, ID=LAST_INSERT_ID(ID)";
... but I can't figure how to add ON DUPLICATE KEY UPDATE to what I'm using:
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
";
e.g.:, pseudo-code
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
ON DUPLICATE KEY UPDATE SET
column1 = value1,
column2 = value2,
column3 = value3,
$id=LAST_INSERT_ID(id)";
$my_id = mysql_insert_id();
";
I would find the latter easier to read. Would appreciate clarification, didn't find an example in the manual.
cheers
I've used ON DUPLICATE KEY UPDATE a lot. For some situations it's non-standard SQL extension that's really worth using.
First, you need to make sure you have a unique key constraint in place. The ON DUPLICATE KEY UPDATE function only kicks in if there would've been a unique key violation.
Here's a commonly used format:
$query = "INSERT INTO $table (column1, column2, column3)
VALUES ('value-1', 'value-2', 'value-3')
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);"
column1 = values(column1) means "Update column1 with the value that would have been inserted if the query hadn't hit the duplicate key violation." In other words, it just means update column1 to what it would've been had the insert worked.
Looking at this code, it doesn't seem correct that you're updating all three of the columns you're trying to insert. Which of the columns has a unique constraint on it?
EDIT: Modify based on 'SET' format of mysql insert statement per the question from the OP.
Basically to use ON DUPLICATE KEY UPDATE, you just write the insert statement as you normally would, but add the ON DUPLICATE KEY UPDATE clause tacked onto the end. I believe it should work like this:
INSERT INTO $table
set column1 = 'value-1',
column2 = 'value-2',
column3 = 'value-3'
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);
Again, one of the columns you're inserting has to have a unique index (or a combination of the columns). That can be because one of them is the primary key or because there is a unique index on the table.
Have you tried using REPLACE INTO instead?
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/
Related
Let me explain what I need and canot get :(
I have to DB one i main the other is just getting part of data from the firs one.
This is my code:
foreach($id_product_array AS $id_product) {
$resultf = mysql_query("SELECT * FROM db1_available_product WHERE id_product='".$id_product."'");
while($rowi = mysql_fetch_array($resultf)) {
$aa1=$rowi['id_product'];
$aa2=$rowi['date'];
$aa3=$rowi['available'];
$aa4=$rowi['published'];
mysql_query("INSERT INTO aa_bb.db2_available_product (`id_product`, `date`, `available`, `published`) VALUES ('".$aa1."','".$aa2."', '".$aa3."', '".$aa4."') ON DUPLICATE KEY UPDATE `id_product` = '".$aa1."', `date` = '".$aa2."', `available` = '".$aa3."', `published` = '".$aa4."'");
}
The problem is that this multiples the record in DB2 so I am now in millions!!!
Its set up as cron job on 1h basis.
What I need is ether it checks what is existing and don't touch it or if need on update or insert.
The other solution would be to delete the whole table in DB2 then to insert a fresh one from DB1
You can simplify your query like so:
INSERT INTO tbl2 (column1, column2)
SELECT column1, column2 FROM tbl1
ON DUPLICATE ...
See the documentation
You are looking for MySQL's proprietary REPLACE command. It has the same syntax as a regular INSERT, but it checks for duplicate primary key before inserting, and if it is found it will do an UPDATE instead:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.
Of course you will have to define a unique PK/index on your table that allows this functionality to work.
here is an update!
I solved the problem :)
Thanks s to Niels because he made me rethink my strategy so the solution was simple.
In the DB1 and DB2 there is and ID filed
A added
$aa5=$rowi['id'];
so that made ON DUPLICATE KEY UPDATE work correctly!
foreach($id_product_array AS $id_product) {
$resultf = mysql_query("SELECT * FROM db1_available_product WHERE id_product='".$id_product."'");
while($rowi = mysql_fetch_array($resultf)) {
$aa5=$rowi['id'];
$aa1=$rowi['id_product'];
$aa2=$rowi['date'];
$aa3=$rowi['available'];
$aa4=$rowi['published'];
mysql_query("INSERT INTO aa_bb.db2_available_product (`id`,`id_product`, `date`, `available`, `published`) VALUES ('".$aa5."','".$aa1."','".$aa2."', '".$aa3."', '".$aa4."') ON DUPLICATE KEY UPDATE `id` = '".$aa5."',`id_product` = '".$aa1."', `date` = '".$aa2."', `available` = '".$aa3."', `published` = '".$aa4."'");
}
and it seams that it is working OK!
:)
I want to insert into a MySQL row if the row doesn't exist, or update it if it does exist.
Something like this:
$sqlQuery = "INSERT INTO table (Value1, Value2) VALUES ('$var1', '$var2') WHERE UniqueKey='$id'";
Is something like that possible?
INSERT INTO table (UniqueKey,Value1, Value2) VALUES ('$id','$var1', '$var2')
ON DUPLICATE KEY UPDATE Value1 = '$var1',Value2 = '$var1';
User MySQL's REPLACE command:
$sqlQuery = "REPLACE INTO table (id, Value1, Value2) VALUES ('$id', '$var1', '$var2')";
It works the same as a normal INSERT, but if the primary key (in you case 'id') matches then it will replace all the values specified.
replace into table (UniqueKey,Value1,Value2) values ('$id','$var1','$var2');
replace is similar to insert, however if the unique key exists in table, it will delete first, and than insert.
I need to update column values (say column2) with concatenation of two string variables (say str1 & str2) with another column (say column1). Final value which I need in column2 is str1 as prefix and str2 as suffix to column1 value.
One way which can be done is with a dummy third column and a total of 4 update queries.
update table set column3 = str1;
update table set column2 = concat(column3, column1);
update table set column3 = str2;
update table set column2 = concat(column2, column3);
But I want to reduce that to a single update without using a dummy column, like below -
update table set column2 = concat($str1, column1, $str2);
I need help in the concat part of the above query.
There's no reason this not to work:
$prefix = mysql_realescape_string($str1);
$suffix = mysql_realescape_string($str2);
$sql = "UPDATE table SET cloumn2 = CONCAT('$prefix', column1, '$suffix')";
Assuming you are using PHP, there is your solution:
$query="update table set column2 = concat('$str1', column1, '$str2');";
You were actually very close to solution.
Try something like:
$sql = "UPDATE table SET column2 = CONCAT_WS('-', '$str1', column1, '$str2');";
The first argument for CONCAT_WS is the string character you'd like to concatenate with.
I've seen the following (using the VALUES option):
$query = "INSERT INTO $table (column-1, column-2, column-3) VALUES ('value-1', 'value-2', 'value-3') ON DUPLICATE KEY UPDATE SET column1 = value1, column2 = value2, column3 = value3, ID=LAST_INSERT_ID(ID)";
... but I can't figure how to add ON DUPLICATE KEY UPDATE to what I'm using:
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
";
e.g.:, pseudo-code
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
ON DUPLICATE KEY UPDATE SET
column1 = value1,
column2 = value2,
column3 = value3,
$id=LAST_INSERT_ID(id)";
$my_id = mysql_insert_id();
";
I would find the latter easier to read. Would appreciate clarification, didn't find an example in the manual.
cheers
I've used ON DUPLICATE KEY UPDATE a lot. For some situations it's non-standard SQL extension that's really worth using.
First, you need to make sure you have a unique key constraint in place. The ON DUPLICATE KEY UPDATE function only kicks in if there would've been a unique key violation.
Here's a commonly used format:
$query = "INSERT INTO $table (column1, column2, column3)
VALUES ('value-1', 'value-2', 'value-3')
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);"
column1 = values(column1) means "Update column1 with the value that would have been inserted if the query hadn't hit the duplicate key violation." In other words, it just means update column1 to what it would've been had the insert worked.
Looking at this code, it doesn't seem correct that you're updating all three of the columns you're trying to insert. Which of the columns has a unique constraint on it?
EDIT: Modify based on 'SET' format of mysql insert statement per the question from the OP.
Basically to use ON DUPLICATE KEY UPDATE, you just write the insert statement as you normally would, but add the ON DUPLICATE KEY UPDATE clause tacked onto the end. I believe it should work like this:
INSERT INTO $table
set column1 = 'value-1',
column2 = 'value-2',
column3 = 'value-3'
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);
Again, one of the columns you're inserting has to have a unique index (or a combination of the columns). That can be because one of them is the primary key or because there is a unique index on the table.
Have you tried using REPLACE INTO instead?
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/
I've found a few answers for this using mySQL alone, but I was hoping someone could show me a way to get the ID of the last inserted or updated row of a mysql DB when using PHP to handle the inserts/updates.
Currently I have something like this, where column3 is a unique key, and there's also an id column that's an autoincremented primary key:
$query ="INSERT INTO TABLE (column1, column2, column3) VALUES (value1, value2, value3) ON DUPLICATE KEY UPDATE SET column1=value1, column2=value2, column3=value3";
mysql_query($query);
$my_id = mysql_insert_id();
$my_id is correct on INSERT, but incorrect when it's updating a row (ON DUPLICATE KEY UPDATE).
I have seen several posts with people advising that you use something like
INSERT INTO table (a) VALUES (0) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
to get a valid ID value when the ON DUPLICATE KEY is invoked-- but will this return that valid ID to the PHP mysql_insert_id() function?
Here's the answer, as suggested by Alexandre:
when you use the id=LAST_INSERT_ID(id) it sets the value of mysql_insert_id = the updated ID-- so your final code should look like:
<?
$query = mysql_query("
INSERT INTO table (column1, column2, column3)
VALUES (value1, value2, value3)
ON DUPLICATE KEY UPDATE
column1 = value1,
column2 = value2,
column3 = value3,
id=LAST_INSERT_ID(id)
");
$my_id = mysql_insert_id();
This will return the right value for $my_id regardless of update or insert.
You could check if the Query was an insert or an update ( mysql_affected_rows(); returns 1 on insert and 2 on update).
If it was an insert use mysql_insert_id, if it was an update you'd need another Query.
<?php
$query ="INSERT INTO TABLE (column1, column2, column3) VALUES (value1, value2, value3) ON DUPLICATE KEY UPDATE SET column1=value1, column2=value2, column3=value3";
mysql_query($query);
if(mysql_affected_rows() == 1) { $id = mysql_insert_id(); }
else { // select ...
}
?>
I know it's not excatly what your looking for but it's the best i could come up with
Although not using mysql_insert_id() and ON DUPLICATE KEY UPDATE, alternative great way to get the value of any field when updating another found here:
UPDATE table SET id=(#tempid:=id) , .... LIMIT 1;
SELECT #tempid;
I used it having table with (id,status) 'id' primary index auto-increment, and 'status' was the field upon which update was made, but i needed to get 'id' of the updated row. This solution also proof to race conditions as mysql_insert_id().
This is my solution where you put the data into a single array and it's automatically duplicated/populated into the "INSERT INTO .. ON DUPLICATE UPDATE .. " query.
It's great for maintainability, and if you want you can make it a function / method too.
// save to db:
$qData = [
"id" => mysql_real_escape_string($email_id),
"synd_id" => mysql_real_escape_string($synd_id),
"campaign_id" => mysql_real_escape_string($campaign_id),
"event_id" => mysql_real_escape_string($event_id),
"user_id" => mysql_real_escape_string($user_id),
"campaign_name" => mysql_real_escape_string($campaign_name),
"subject" => mysql_real_escape_string($subject),
"from_name"=> mysql_real_escape_string($from_name),
"from_email"=> mysql_real_escape_string($from),
"content"=> mysql_real_escape_string($html),
"link_to_template" => mysql_real_escape_string($hash),
"ext_campaign_id" => mysql_real_escape_string($ext_campaign_id),
"ext_list_id"=> mysql_real_escape_string($ext_list_id),
];
$q = "INSERT INTO email_campaigns (".
// i.e create a string like `id`, `synd_id`, `campaign_id`.. with linebreaks for readability
implode(", \n", array_map(function($k){ return "`$k`"; }, array_keys($qData)))
.")
VALUES (".
// i.e '20', '532', '600' ..
implode(", \n", array_map(function($v){ return "'$v'"; }, array_values($qData)))
." ) ON DUPLICATE KEY UPDATE ".
// i.e `synd_id`='532', `campaign_id`='600' ...
// id & link_to_template table keys are excluded based on the array below
implode(", \n", array_filter(array_map(function($k, $v){ if(!in_array($k, ['id', 'link_to_template']) ) return "`$k`='$v'" ; }, array_keys($qData), array_values($qData)))) ;