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';
Related
I want to insert or update a record in a table. If it doesn't exist, it should be inserted. If it exists, then I only want to update the record if a certain condition is met. Is there a way to do this using a single INSERT statement? Something like this:
CREATE TABLE test1 SELECT 1 id, now() dt;
ALTER TABLE test1 ADD PRIMARY KEY (id);
INSERT IGNORE INTO test1 (id, dt) VALUES
(1, '2023-02-06 13:00:00')
ON DUPLICATE KEY UPDATE dt = VALUES(dt) WHERE dt = somedatetime;
-- i.e. always insert, but only update dt if existing dt value is something specific
I know I can do this using a transaction, I'm just wondering if something like this can be done in a single statement.
I was trying things out while writing the question and I found this to be one solution:
INSERT IGNORE INTO test1 (id, dt)
SELECT 1, '2023-02-06 13:00:00'
FROM test1
WHERE (NOT EXISTS(SELECT * FROM test1 WHERE id = 1))
OR (id = 1 AND dt = somedatetime)
ON DUPLICATE KEY UPDATE dt = VALUES(dt);
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);
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
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.
I am trying to read value from a table them insert it into another table only if the staring that I am trying to insert does not already exist in the table.
I have tried to use the ON DUPLICATE KEY clause but I get a syntax issue that i am unable to fix.
this is my query
SELECT Field1 FROM RSF
INSERT INTO result_codes(result_code_title, created_by)
VALUES (Field1, '2')
ON DUPLICATE KEY UPDATE result_code_title = Field1;
The clause is INSERT INTO ... SELECT and not SELECT ... INSERT INTO. Therefore:
INSERT INTO result_codes( result_code_title, created_by )
SELECT Field1, '2'
FROM RSF
ON DUPLICATE KEY
UPDATE result_code_title = Field1;
I think that should work.
Since you only want to insert only if the string doesn't already exist; you should be better off using INSERT INGORE:
INSERT IGNORE INTO result_codes( result_code_title, created_by )
SELECT Field1, '2'
FROM RSF
Use INSERT IGNORE instead.
INSERT IGNORE INTO result_codes(result_code_title, created_by)
SELECT Field1, '2'
FROM RSF
It detects via a primary key or unique index, if a row already exists and doesn't attempt to insert if this is the case.