Mysql: ON DUPLICATE KEY UPDATE: Only update when value has changed - mysql

I have a mysql table where I use this query:
INSERT INTO `stats` (`id`, `shop`, `price`, `timestamp`)
VALUES (NULL, '$shop', '$price', 'timestamp') ON DUPLICATE KEY UPDATE price='$price'
The shop column is unique. "Id" = primary key. The timestamp column is updated by mysql: on update CURRENT_TIMESTAMP
Data in the dB:
row: id=1, shop=viacom, price=5, timestamp=1524183480
Case 1: Row to be inserted: shop=viacom, price=6
Result: The existing row is updated
Case 2: Row to be inserted: shop=viacom, price=5 (<-- price has NOT changed)
Result: The existing row is NOT updated
I would like to get case 2 working. I can handle it with php-code, but I'd rather let Mysql do that job. Any ideas? (I tried adding a Where Clause like $shop=shop)

Since the shop column is a UNIQUE key, you can remove the id column and use the below.
replace into stats (shop, price) values ('$shop', '$price')
If shop already exists, then the price is updated. Else a new shop will be inserted. Is this what you want?

Try to update the timestamp column manually:
INSERT INTO `stats` (`shop`, `price`) VALUES ('$shop', '$price')
ON DUPLICATE KEY UPDATE price='$price', timestamp = NOW();
=========
Option #2:
If you want to do it in MySQL, create stored procedure and call the stored procedure from PHP code.
CREATE PROCEDURE `createOrUpdatePrice` (ex_shop varchar(255),ex_price int(11))
BEGIN
declare occures tinyint(1);
SELECT COUNT(`shop`) into occures from `stats` WHERE shop = ex_shop;
IF occures = 0 Then
INSERT INTO `stats` (`id`, `shop`, `price`) VALUES (NULL, ex_shop, ex_price);
ELSE
UPDATE `stats` SET price = ex_price where shop = ex_shop;
END IF;
END

Related

What will be the insert query depends on previous data in same table?

I want to insert a row if it's one specific column value is not still available. If available, i want to update that row. Otherwise it will insert normally. What should be the SQL query for this task?
For example:
id, Product_id, user_id, quantity are the table's attributes
Considering,
[1, 450, 56, 2] is in table.
If i want to insert [2,450,56,3] then it will not create new row. It will update the previous row. Like [1,450,56,5].
I'd start by creating a unique constraint on the combination of product_id and user_id (or even a primary key if you don't have one on the table yet):
ALTER TABLE mytable
ADD CONSTRAINT uc_product_user UNIQUE (product_id, user_id);
And then you can use the on duplicate clause in an insert statement:
INSERT INTO mytable
VALUES (2, 450, 56, 3)
ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity);
You could set product_id and user_id as the primary key or unique key on the table and then use INSERT .. ON DUPLICATE KEY UPDATE. You can find more information about that here.
It would look something like:
INSERT INTO t1 (id, product_id, user_id, quantity) VALUES (2,450,56,3)
ON DUPLICATE KEY UPDATE quantity = quantity + 3;
Alternatively, you're going to have to write your own merge statement (MySql doesn't support merge, but you can fake it)
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_updateValue`(IN prm_productid INT, IN prm_userid INT, IN prm_quantity INT)
BEGIN
-- Check that the case actually exists first.
DECLARE vExists INT;
SELECT COUNT(1) INTO vExists FROM YourTable WHERE product_id = prm_orderid AND user_id = prm_userid;
IF vCaseExists = 1 THEN
UPDATE YourTable SET quantity = prm_quantity WHERE product_id = prm_orderid AND user_id = prm_userid;
ELSE
INSERT INTO YourTable (id, product_id, user_id, quantity) VALUES (2,450,56,3);
END IF;
END$$
DELIMITER ;

MySQL Trigger with IF statement

I'm trying to create my first MYSQL trigger, when an Inserted record with a role_id of 4 is inserted, I want it to insert another record using the same values but with a role_id of 5.
My best effort is:
CREATE TRIGGER auto_insert_member
AFTER INSERT ON staff_role
FOR EACH ROW
BEGIN
IF (NEW.role_id = 4) THEN
INSERT INTO staff_role
SET
start_date = NEW.start_date,
end_date = NEW.end_date,
person_id = NEW.person_id,
role_id = 5
END IF
END
I can't make it work and phpMyAdmin error messages are not helpful. What am I doing wrong?
It is possible that the syntax error is due to the mixing of the UPDATE and INSERT method:
UPDATE TABLE
SET COLUM1 = VALUE1,
COLUM2 = VALUE2;
INSERT INTO TABLE
(COLUM1, COLUM2)
VALUES (VALUE1, VALUE2);

MYSQL Check for duplicates and only insert if another field is a certain value

If I'm inserting data into a table with the following fields:
serialNumber active country
I need to only insert duplicate serialNumbers if active is no.
So for example: I want to insert a record with serialNumber 1234.
If the serial number doesn't already exist in the table go ahead and add it. If it does already exist, check the value of 'active' active is yes then don't add the new record, if it's no then do add the record.
Any ideas how to achieve this in MYSQL?
If the table lacks the necessary unique keys and you do not have permission, or don't want to set the keys you would need, you can use this alternative:
INSERT INTO `table1`
(`field1`,
`field2`)
SELECT value1,
value2
FROM (SELECT 1) t_1
WHERE NOT EXISTS (SELECT 1
FROM `table1`
WHERE `field1` = value1
AND `field2` = value2);
For yor question it could be written as
INSERT INTO `activity`
(`serialNumbers`,
`active`)
SELECT 1234,
'yes'
FROM (SELECT 1) t_1
WHERE EXISTS (SELECT 1
FROM `activity`
WHERE `serialNumbers` = 1234
AND `active` = 'no');
You can use the ON DUPLICATE KEY statement after an INSERT INTO query to update the row if it already exists. Documentation : https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (serialNumber , active, country) VALUES (1010, 'no', 'FR')
ON DUPLICATE KEY UPDATE active='yes';
You can use the insert ... on duplicate key update in MySQL. It is similar to the MERGE used in other SQL databases, but MySQL does not provide the MERGE statement so this is the next best.
INSERT INTO TABLE (serialNumber, active, country)
VALUES (1234, 'active', 'GB') ON DUPLICATE KEY UPDATE country = 'ND';
Also, use INSERT IGNORE if you don't want to generate errors.

Mysql query to update row if exists?

I need an If, then, else query in mysql,
tried out the below,
if exists( select * from data_table where user_id =1 and link_id = 1) then update data_table set is_view = 1 where user_id = 1 else insert into data_table...
what is the correct way to do this?
if you only need to do this in mysql, then search insert on duplicate key. Or you can use a stored procedure. Check INSERT ... ON DUPLICATE KEY UPDATE Syntax
insert into data_table (user_id, link_id, other_column)
values (1, 1, 'value to insert or uodate')
on duplicate key update other_column='value to insert or update';

MYSQL trigger see if record exists first?

So I have a trigger that works on update. Totally works fine.
Insert in cars(date, id, parent_id) values (date, ford, 2)
What I need to do is to actually check to see if the parent_id already exists. If it does do nothing but if it does not exist then do the insert statement.
right now i have
SET #myVar1 = (SELECT parent_id from cars where parent_id = NEW.id);
IF #myVar1 = NULL;
Insert in cars(date, id, parent_id) values (date, ford, 2);
ENDIF;
I keep getting sysntax error. How am I writing this worng?
The problem is on this line:
Insert in cars(date, id, parent_id) values (date, ford, 2);
The in should be INTO. That's the syntax error.
That said, you might be better served with an INSERT...ON DUPLICATE KEY or REPLACE INTO statement rather than an on-update trigger. Be careful with REPLACE INTO though, as it can be dangerous (but the danger can be somewhat mitigated by using transactions).
dunno if this what you really need. but you can try this one
SET #myVar1 = (SELECT parent_id from cars where parent_id = NEW.id);
IF (#myVar1 is NULL) then
Insert into cars(`date`, id, parent_id) values (date(), new.`name`, new.id);
END IF;
or
Insert into cars(`date`, id, parent_id) values (date(), new.`name`, new.id) on duplicate key update `date`=date();
on mysql must be "end if" not "endif".
new.name is assumes that id field on car from trigger table
you can use on duplicate key update if cars table use primary key or unique key like mention above
and if you doesn't want to change any record if exists then after key update change to id=id or you can use any field.