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);
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 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
My question is. I have the table 'popular' with fields 'id', 'title', 'popularity' in MySQL. I need insert info into field "title", if info not exists or increment value of 'popularity', if info exists. What is the best practice to do it?
INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO popular (title, popularity) VALUES (:the_title, 1)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), popularity = popularity + 1
Make sure you have an unique constraint on title
id = LAST_INSERT_ID(id) allows you to get the id of the record you inserted/updated using LAST_INSERT_ID (or the equivalent function for your MySQL API). If you don't need the id you can remove it from the UPDATE list.
sample code:
if exists (select * from contact where name = #name) then
select -1;
else
insert into contact(name) values(#name);
select last_insert_id();
end if;
reference:
http://ask.sqlservercentral.com/questions/88038/best-mysql-practice-to-insert-a-record-if-it-does.html
http://bugs.mysql.com/bug.php?id=19243
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/
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';
I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE '12gfa' not in ( select id from mytable)' at line 3
First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.
You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
This will insert a new row, unless a row already exists with a duplicate key, it will update it.
DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;
or just make an attribute name as UNIQUE