update if exists [duplicate] - mysql

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I update if exists, insert if not (aka upsert or merge) in MySQL?
I have a table with the columns user, category and score. I want to run an insert that, if this user/category combination already exists instead just updates the score. Both the user and the category column can have the same value many times but each specific user/category combination may only exist on one single row. How can I do this?
Many thanks

For this example, let's call your table scores:
Make sure you have a unique index
ALTER TABLE scores ADD UNIQUE INDEX user_category_ndx (user,category);
Now run this to replace:
INSERT INTO scores (user,category,score) VALUES ('username','mycat',127)
ON DUPLICATE KEY UPDATE score = VALUES(score);
If your updating the score means add up scores, then do this:
INSERT INTO scores (user,category,score) VALUES ('username','mycat',127)
ON DUPLICATE KEY UPDATE score = score + VALUES(score);
Give it a try!
UPDATE 2011-08-28 09:00 EDT
If you want to keep just high scores and then add the unique index, here is what you must do:
CREATE TABLE scores_new LIKE scores;
ALTER TABLE scores_new ADD UNIQUE INDEX user_category_ndx (user,category);
INSERT INTO scores_new (user,category,score)
SELECT user,category,MAX(score) FROM scores GROUP BY user,category;
ALTER TABLE scores RENAME scores_old;
ALTER TABLE scores_new RENAME scores;
#
# Drop old table if no longer needed
#
DROP TABLE scores_old;
UPDATE 2011-08-28 10:53 EDT
Run this to keep maximum score:
INSERT INTO scores (user,category,score) VALUES ('username','mycat',127)
ON DUPLICATE KEY UPDATE score = GREATEST(VALUES(score),score);

What you want is INSERT ... ON DUPLICATE KEY UPDATE. Make sure you have a unique index defined on user, category. See http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

Related

how to combine three columns and remove duplicates in sql

I have table with 7 columns where I want to combine three column and want to remove duplicates. Your help will be appreciated.
I'm guessing you want to update the table SERIAL_NUMBERS with just a single row of combined warranty_indicator, account, date_sold data. If that's true then I will suggest the following.
Duplicate SERIAL_NUMBERS table:
CREATE TABLE SERIAL_NUMBERS_NEW LIKE SERIAL_NUMBERS;
Add unique constraint - combination of warranty_indicator, account, date_sold:
ALTER TABLE SERIAL_NUMBERS_NEW
ADD CONSTRAINT Index1 UNIQUE (warranty_indicator,account,date_sold);
Insert data from SERIAL_NUMBERS table to SERIAL_NUMBERS_NEW using INSERT IGNORE ; to ignore duplicates:
INSERT IGNORE INTO SERIAL_NUMBERS_NEW
SELECT * FROM SERIAL_NUMBERS;
Rename old and new table:
RENAME TABLE SERIAL_NUMBERS TO SERIAL_NUMBERS_OLD;
RENAME TABLE SERIAL_NUMBERS_NEW TO SERIAL_NUMBERS;
Check data:
SELECT * FROM SERIAL_NUMBERS_OLD;
SELECT * FROM SERIAL_NUMBERS;
Keep in mind that any future data inserted will treat duplicates according to the unique constraint. Therefore, if you have program running the INSERT syntax, make sure you update it to INSERT IGNORE.
Demo fiddle

MySQL - Insert Multiple Records or Update Multiple Records If Exists

I want to INSERT a new record into my database if it is no exists, otherwise it will UPDATE those existing records.
I did search on Stackoverflow, but none of the result can solve my issue.
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query
TABLE STRUCTURE
SCENARIO
There are a lot of records inside Purchase Details table. So the only Unique ID is only purchase_id.
I want to update the amount which have the same product_id. Refer to the table.
Below is the SQL Query I have tried so far.
INSERT INTO `purchase_details` (`product_id`, `amount`)
VALUES (1583, 0)
ON DUPLICATE KEY UPDATE amount = 0
The query shows 1 row affected.
But total has 146 rows which mean this query is not working.
PROBLEM
ON DUPLICATE KEY UPDATE only allow to inserted a row that would cause a duplicate value in a UNIQUE index or PRIMARY KEY
If I understand your question correctly, you want to update the other existing rows of your table which have the same product_id as the new one being inserted with the newly provided amount value.
Since product_id is not a unique column in purchase_details table, it will not consider this scenario for ON DUPLICATE KEY UPDATE condition. Ergo, 1 row affected.
To achieve what you want, you need to CREATE TRIGGER.
Like this:
DELIMITER $$
CREATE TRIGGER ins_check
AFTER INSERT ON purchase_details
FOR EACH ROW
BEGIN
UPDATE purchase_details
SET amount = NEW.amount
WHERE product_id = NEW.product_id;
END;$$
DELIMITER ;

Issues with MySQL inserting columns below desired location

I have been having some frustration attempting to add data values to this table students. I have all the other data values and have dropped and created the column student_id. However, when trying to add the data with this query:
insert into students(student_id) values('1'),('2'),('3'),('4'),('5');
The data does not insert correctly, as it creates new columns below the first 5 which contain data.
It must be because of my not null values, but I can't not have the not null identifier.
Is there a query command that allows me to change data within already existing value-filled columns? I have been unsuccessful in finding this so far.
Here are some images to explain the problem further.
The query I have made to add my values to the table:
The data was inserted but as it is underneath the columns I need to map with a foreign key, I cannot use the column as the top 5 values are still my not null default, which is required to let me create the foreign key
Looks like you already have your records initially created without the student_id field, you want to UPDATE the current records but you're actually INSERTING new records.
You're meant to update your students with update statements such as "UPDATE students SET student_id = X where condition = Y"
Then it looks like your student_id is your primary key which you should set to AUTO_INCREMENT value.
Regards
INSERT is the wrong command since you want to update existing rows. The problem here lies within the fact that the order of the rows is nondeterministic and I think you cannot update them in one statement. One solution would be as follows:
UPDATE students SET student_id = 1 WHERE first_name = 'Berry';
UPDATE students SET student_id = 2 WHERE first_name = 'Darren';
I hope you really do have only 5 columns to update :-)

Insert if not exist and Update if exist

I have three columns on my database table
user_id, post_id, and vote
I want to insert a new data if user_id and post_id don't exist. But if both columns user_id and post_id exist i will be able to update 'vote' column value. I set user_id to be unique but it proves to be not working since i want user to insert votes on different post.
The query below only updated the value of vote since user_id already exist. I want to have it updated if and only if user_id and post_id existed
I used this sql query
INSERT INTO polls (user_id,post_id,vote) VALUES (1,2,5)
ON DUPLICATE KEY UPDATE vote= ?;
Here's my problem
You must create unique key combination
Create unique index your_index_name on yourtable (field_one,field_two),
then do the insert into , on duplicate key logic
It is absolutely logical that your code does not work as intended, because your only key is user_id, thus if you want to check the uniqueness of user_id AND post_id, then you should set it as so.
Don't think you can do it purely in MySQL :*( post_id would have to be unique and you said that does not fit your business logic. Furthermore, if multiple keys are detected, they are joined by an OR in the resulting query, which will further complicate things for you. Here's an excerpt from the manual, where a and b are keys involved in the ON DUPLICATE KEY query:
If a=1 OR b=2 matches several rows, only one row is updated. In general, you should try to avoid using an ON DUPLICATE KEY UPDATE clause on tables with multiple unique indexes.

MySql Trigger INSERT... ON DUPLICATE KEY UPDATE not recognising columns

I have two tables in a Mysql database: "stock_pricing" and "DATA_IMPORT"
columns in first table: STOCK_ID, DATE, LAST_CLOSE_DOM_CURR
columns in second table: STOCK_ID, DATE, ADJ_CLOSE
The first table has an index on stock_id and date together. These have been defined as UNIQUE.
The second table has no index at all.
The second table has incoming data. On this table there is a BEFORE INSERT trigger that inserts incoming data into the first table.
If upon the insert trigger the combination of STOCK_ID and DATE violates the UNIQUE index of the first table, the ON DUPLICATE KEY UPDATE part of the trigger is fired.
I have tried every combination I can think of, but the trigger does not recognise my column names, any thoughts? Many thanks.
BEGIN
INSERT INTO stock_pricing (`STOCK_ID`, `DATE`, `LAST_CLOSE_DOM_CURR`)
VALUES (DATA_IMPORT.STOCK_ID, DATA_IMPORT.DATE, DATA_IMPORT.ADJ_CLOSE)
ON DUPLICATE KEY UPDATE
stock_pricing.STOCK_ID= DATA_IMPORT.STOCK_ID, stock_pricing.DATE= DATA_IMPORT.DATE, stock_pricing.LAST_CLOSE_DOM_CURR= DATA_IMPORT.ADJ_CLOSE;
END
You are referencing a table called data_import with no from clause. This is fixed using insert . . . select:
INSERT INTO stock_pricing (`STOCK_ID`, `DATE`, `LAST_CLOSE_DOM_CURR`)
SELECT DATA_IMPORT.STOCK_ID, DATA_IMPORT.DATE, DATA_IMPORT.ADJ_CLOSE
FROM DATA_IMPORT
ON DUPLICATE KEY UPDATE
stock_pricing.STOCK_ID= DATA_IMPORT.STOCK_ID, stock_pricing.DATE= DATA_IMPORT.DATE, stock_pricing.LAST_CLOSE_DOM_CURR= DATA_IMPORT.ADJ_CLOSE;
A more typical way of writing such a query is:
INSERT INTO stock_pricing (`STOCK_ID`, `DATE`, `LAST_CLOSE_DOM_CURR`)
SELECT di.STOCK_ID, di.DATE, di.ADJ_CLOSE
FROM DATA_IMPORT di
ON DUPLICATE KEY UPDATE STOCK_ID = VALUES(STOCK_ID),
DATE = VALUES(DATE),
LAST_CLOSE_DOM_CURR = VALUES(LAST_CLOSE_DOM_CURR);
For ON DUPLICATE KEY UPDATE to work, you need a unique index or primary key. I assume you have these.
Finally, this code looks a bit strange for a trigger, because there are no references to NEW or OLD. If you are still having trouble with the trigger, then ask another question and include the full code for the trigger.