ON DUPLICATE KEY UPDATE - add to existing value - mysql

I have SQL (MySQL 5.x) query like:
INSERT INTO table (val1),
ON DUPLICATE KEY UPDATE `val1` = VALUES(`val1`)
And this works fine.
Now i need to update it with a sum of VALUES(val1) + ruby variable.
INSERT INTO table (val1),
ON DUPLICATE KEY UPDATE `val1` = VALUES(`val1`) + #{ruby_variable}
throws me an error.
(Ruby here is just an example, actually i need to sum VALUES(val1) + integer)
How it could be done?

Right at the top of the fine manual you will see an example of exactly the sort of thing you're trying to do:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
So you're looking for this:
connection.execute(%Q{
INSERT INTO table (val1) VALUES(#{connection.quote(x)})
ON DUPLICATE KEY UPDATE `val1` = `val1` + #{connection.quote(ruby_variable)}
})
Where x is what you're trying to insert and ruby_variable is what you want to add to val1 when there is a duplicate. You need a VALUES for the INSERT, not for the ON DUPLICATE.

Related

How to insert data into some columns if they don't exist and update them if they do exists using mysql

For example
INSERT INTO tests(test1, test2,test3) values(10,20,15).
if these values exists already, update or overwrite it.
For the query you need a unique Key constraints, so that the update get processed.
INSERT INTO tests(test1, test2,test3) values(10,20,15)
ON DUPLICATE KEY UPDATE test1 = VALUES(test1),test2 = VALUES(test2),test3 = VALUES(test3);
see the manual

How do I update if exist, else insert in MySQL

I have table with AUTO_INCREMENT field defined as PRIMARY_KEY.
I have columns like:
vote_id,vote_user_id,vote_ask_id,vote_comment_id,vote_post_id,vote_type,vote_status
I want to INSERT new records but before I do that I want to check if there is a row with columns(vote_user_id,vote_ask_id,vote_type) as same as the new data I want INSERT.
CONDITIONS:
IF ROW EXISTS
THEN UPDATE tableName SET vote_status=new_value, vote_time=new_time
ELSE
INSERT NEW RECORDS
I have searched the internet and learnt about MySQL ..ON DUPLICATE KEY UPDATE.
I have realize this statement will not be helpful to my task since it only checks for DUPLICATE KEY(...PRIMARY_KEY or UNIQUE FIELD).
I have learnt also on MySQL REPLACE INTO ...and likewise this will not be helpful to my problem since that is also bind to PRIMARY_KEY or UNIQUE index.
I learnt I could use MERGE....USING...statements
but this was giving me errors so i read more about it and I relised it only work in SQL server (Microsoft)
Please how best can someone help me solve this?
I tried this on MERGE staments:
MERGE {$votes_table} WITH (HOLDLOCK) AS VT
USING ({$Qid},{$vote_type},{$CUid},{$vote_status}) AS VTS (vote_ask_id,vote_type,vote_user_id,vote_status)
ON( VT.vote_ask_id = VTS.vote_ask_id AND VT.vote_user_id=VTS.vote_user_id AND VT.vote_type=VTS.vote_type)
WHEN MATCHED THEN
UPDATE SET VT.status=VST.vote_status , VT.vote_time='{$current_time}' WHERE VT.vote_user_id=VTS.vote_user_id AND VT.vote_ask_id=VTS.vote_ask_id AND VT.vote_type=VTS.vote_type
WHEN NOT MATCHED THEN INSERT (vote_ask_id,vote_type,vote_status,vote_user_id,vote_time) VALUES('{$Qid}','{$vote_type}','{$vote_up_status}','{$CUid}','{$current_time}')
In MySQL, use ON DUPLICATE KEY:
INSERT INTO tablename (vote_user_id, vote_ask_id, vote_type, . . . )
VALUES (new_vote_user_id, new_vote_ask_id, new_vote_type . . . )
ON DUPLICATE KEY UPDATE vote_status = VALUES(vote_status), vote_time = VALUES(vote_time);
For this to work, you need a unique index/constraint on the columns that define a unique row:
CREATE UNIQUE INDEX unq_tablename_3 ON tablename(vote_user_id, vote_ask_id, vote_type);
You do want insert ... on duplicate key update: in MySQL, this is the right way to do what you want.
To start with, you need to create a unique constraint on the tuple of concerned columns:
create unique index votes_table_unique_idx
on votes_table(vote_user_id, vote_ask_id, vote_type);
Then, you can do something like:
insert into votes_table(vote_user_id, vote_ask_id, vote_type, vote_comment_id, vote_post_id, vote_status)
values(...)
on duplicate key update
vote_comment_id = values(vote_comment_id),
vote_post_id = values(vote_post_id)
vote_status = values(vote_status)

Mysql trigger add number to new value on duplicate key

I'm trying to import data to a new table, but turns out some values from two different columns are duplicate, but it seems to not be working. This is what my trigger looks like:
DELIMITER //
CREATE TRIGGER insert_specificationattributeoption_child AFTER INSERT ON import_specificationattributeoption FOR EACH ROW
BEGIN
INSERT INTO t_virtuemart_customs (virtuemart_custom_id, custom_parent_id, custom_title, show_title, field_type, custom_params, created_on, created_by, ordering, modified_on, modified_by)
VALUES (NEW.option_id, NEW.specification_attribute_id, NEW.option_name, lower(NEW.option_name), 'S', 0, current_time(), 633, NEW.display_order, current_time(), 633)
ON DUPLICATE KEY UPDATE NEW.option_id = NEW.option_id + 5000;
END //
With the trigger I don't get the duplicate key error, but I don't see any key being over 5000. What am I doing wrong there? Would it be better to "find" the highest id and adding the new id to it instead?
Edit: Basically what I want to do is, if I'm inserting a primary key that already exists, change the value I want to insert.
I am not clear what you are trying to do. The trigger must be detecting the duplicate key because no duplicate error is being shown but UPDATE NEW.option_id = NEW.option_id + 5000 has no effect on the table. If you want to amend the table then the syntax would be UPDATE option_id = NEW.option_id + 5000 -note this also amends the next auto_increment value to NEW.option_id + 5000 + 1.

How to make insert or delete?

Structure table:
id (int primary key)
name (varchar 100)
date(datetime)
For insert I use query:
INSERT INTO table (name, date) VALUES ('t1','$date');
For delete row I use query:
DELETE FROM table WHERE name = 't1';
I would like want how make 1 query: first insert, if row with it name already exist, than delete row, and insert again.
Tell me please how to make it?
Create a UNIQUE index over your name column:
ALTER TABLE `table` ADD UNIQUE (name);
If you genuinely want to "delete row and insert again", then you can use REPLACE instead of INSERT. As documented:
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.
Therefore, in your case:
REPLACE INTO `table` (name, date) VALUES ('t1','$date');
However, if instead of deleting the existing record and then inserting a new one you merely want to update the existing record, you can use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO `table` (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = VALUES(date);
The most material difference is in the treatment of columns for which you do not provide explicit values (such as id in your example): REPLACE will result in the new record having the default value, whereas INSERT ... ON DUPLICATE KEY UPDATE will result in the old value being retained.
What you want to do is use MySQL's on duplicate update feature.
Can be used like this :
INSERT INTO table (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE name=VALUES(name),dateVALUES(date);
Of course for that to happen a dupliate violation must occur.
insert into table (name, date) values('t1','$date') on duplicate key update name=values(name), date=values(date)
Are you looking for an update query?
Update will set a value on an already existing row.
UPDATE table SET date = '$newdate' WHERE name = 't1';
The best way to do this is using the mysql methods together with your query.
If you make the 'name' field unique:
id (int primary key)
name (varchar 100) NOT NULL UNIQUE
date(datetime)
And alter the query to:
INSERT INTO table
(name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = "$date"

Why is this MySQL query causing an error?

Query:
INSERT INTO `metadata` (`group_id`, `key`, `value`)
VALUES ("19", "originality", "2")
ON DUPLICATE KEY UPDATE (`group_id` = `19`, `key`=`originality`, `value`=`2`)
The table:
group_id | key | value
----------------------------------------
group_id and key both have a UNIQUE index.
The error happens when I try to run the query when a row already exists with the id 19. The way I want the query to function is, if there is no row with that id, insert it and if there is update it instead of inserting a new row.
The error message I get is the typical:
I'm not sure if a ( should follow the UPDATE keyword - I think not. So try
ON DUPLICATE KEY UPDATE `group_id` = 19, `key`='originality', `value`=2
(or replace group_id with submission_group_id - your error message doesn't seem to match the original query)
you can only use ` on table columns and table names, not for data.
data should use ' or "
like:
ON DUPLICATE KEY UPDATE `group_id` = 19, `key`="originality", `value`=2
The quote tag must be the ' character not the ` character.
if there is no row with that id, insert it and if there is update it instead of inserting a new row.
If you want to do this you should try statement like:
IF EXISTS (SELECT * FROM sometable WHERE ColumnName='somevalue')
UPDATE sometable SET (...) WHERE ColumnName='somevalue'
ELSE
INSERT INTO Table1 VALUES (...)