My SQL INSERT INTO based on conditions - mysql

I have a table called autosaves where i my web-app saves every 4 second a user autosave in case my web-app crashes.
autoSaves
customerId
designType
autosaveFile
The condition is this:
If a customerId and designtype already exists, update the row with these values(customerId designType autosaveFile)
otherwise if the 2 conditions i mentioned do not exist then create a new row with the new values.
I have come accross the Insert Into statement but i cannot seem to understand how to formulate it so that it updates when the 2 conditions are met.

You need to create a unique index on the customerId and designType columns:
CREATE UNIQUE INDEX ix_cust_design ON autoSaves (customerId, designType);
Then you can use the following INSERT statement:
INSERT INTO autoSaves (customerId, designType, autosaveFile)
VALUES (#id, #type, #file)
ON DUPLICATE KEY UPDATE autosaveFile = VALUES(autosaveFile)

Related

How do I get the updated rows id when using on duplicate update in a inserting multiple rows query?

So I have two tables, Person(id, name, phone, partner), Partner(id, personA, personB). Person table has unique key (name, phone) and the id is auto-incremented.
I have an insert query that insert multiple rows which will first check if name or phone is the same, then decide whether update the partner fields or do a normal inert.
INSERT INTO Table1(name, phone, partner)
VALUES ("name1", "phone1", "partner1"), ("name2", "phone2", "partner2")
ON DUPLICATE KEY UPDATE partner = VALUES(partner);
So the point is, every time I execute this query, it will possibly update or insert multiple rows.
Is there a way that I can get those updated row's ids so that I can insert the ids to the Partner table? I don't need to update the Partner table, just insert.
Following question will be, I can use row_count before and after the query been executed to get how many rows been inserted and their id's range. But is there any better way to work around with this?
Thanks!

insert into 2column table, avoiding duplicate records

I have a table with 2 columns, userid and messageid. I am updating it automatically through a php script, but I can't get a working insert statement. I don't mind if there are duplicates of userid, or duplicates of messageid (in fact there should be duplicates of both), I just don't want any duplicate of the same combination of userid and messageid. Is there any way to write a query that will do this for me, or do I have to handle it at the php level?
I've probably tried 20 different queries that I found on here and google, but have not gotten it right. This was the last thing I tried:
INSERT INTO interests_join (userid, interestid)
VALUES (1, 4)
WHERE NOT EXISTS
(SELECT userid, interestid FROM interests_join WHERE userid = 1 AND interestid = 4)
You can add a UNIQUE KEY, sql will refuse to insert a new row that is a duplicate of an existing one.
ALTER TABLE `interests_join` ADD UNIQUE `row` (`userid`, `interestid`);
Then you'll have to check from PHP if the query was successful or not (error #1062). You can't apply the key if there are duplicate rows, you have to remove them first .

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 ;

How do I INSERT a new row or UPDATE an existing row effeciently?

So I have a 'recently_viewed' table with columns
product|user|time
However, if a user views a product they have already viewed, it will create a new row. What is the most efficient way of covering this possibility (while keeping the possibility that it is the first time they viewed it)? overwriting the old TIME they viewed it or deleting the old table row (and simultaneously creating the new row)? I can think of some inefficient ways to do it (querying first to see if it's in the table, but this requires multiple statements), but I suspect there is something far more efficient.
INSERT INTO recently_viewed ...
Sincere thanks for any help. It is greatly appreciated from an amateur.
You can check whether record for user exists in recently_viewed,
IF EXISTS (SELECT * FROM recently_viewed WHERE user = "user_id")
BEGIN
#UPDATE query
END
ELSE
BEGIN
#INSERT query
END
You can use define (product, user) as UNIQUE, for example you can set it as the PRIMARY KEY of your table:
CREATE TABLE tablename (
product INT,
user INT,
time DATETIME,
PRIMARY KEY (product, user)
);
(or you can also create a UNIQUE index) and then use an INSERT INTO ... ON DUPLICATE query:
INSERT INTO tablename (product, user, `time`)
VALUES (1, 1, '2015-01-01 10:00:00'),
ON DUPLICATE KEY UPDATE `time`=VALUES(`time`);
Please see a working example here.
I would strong suggest using on duplicate key update. This starts with a unique index on user/product:
create unique index idx_recently_viewed_user_product on recently_viewed(user, product);
Then:
insert into recently_viewed(user, product, time)
values ($user, $product, $time)
on duplicate key update time = values(time);

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.