Use ON DUPLICATE KEY UPDATE to update row with MySQL - mysql

I've the following table structure:
Table ___Availabilities :
|--------|------------|------------|------------|
| AVA_Id | AVA_RoomId | AVA_Date | AVA_Status |
|--------|------------|------------|------------|
| 1 | 47 | 2019-03-11 | NoData |
| 2 | 48 | 2019-03-22 | Book |
| 3 | 48 | 2019-03-23 | Book |
|--------|------------|------------|------------|
I want to UPDATE the AVA_Status only if AVA_RoomId and AVA_Date are know in a row of the table. If not, INSERT a new row.
So my query is this one:
INSERT INTO ___Availabilities
(AVA_Id, AVA_RoomId, AVA_Date, AVA_Status)
VALUES('', '103', '2019-04-04', 'Open')
ON DUPLICATE KEY UPDATE
`AVA_RoomId`='47',
`AVA_Date`='2019-03-11'
But it doesn't work as it added a new row whereas it should update the row where AVA_RoomId = 47 and AVA_Date = 2019-03-11.
Why my query is not working please ?
Thanks.

Assuming there is a UNIQUE INDEX(AVA_RoomId, AVA_Date)
You might want to update the AVA_Status when the combination of room and date already exists:
INSERT INTO ___Availabilities
(`AVA_RoomId`, `AVA_Date`, `AVA_Status`)
VALUES('103', '2019-04-04', 'Open')
ON DUPLICATE KEY UPDATE
`AVA_Status` = VALUES(`AVA_Status`),
As #Barmar already explained, if not already done, you can still add an index after table creation:
ALTER TABLE `___Availabilities`
ADD UNIQUE INDEX `uq_room_date` (`AVA_RoomId`, `AVA_Date`)
;

Related

Create Trigger : update table column by inserting data into another table rows

Please Help me to create triggers,
I have 2 tables of
data
+---------+------------+-------+-------+
| id | info_id | rate | qty | total |
+----+---------+------------+----------+
| 80 | 10 | 150 | 5 | 750 |
+----+---------+-------+-------+-------+
| 81 | 10 | 50 | 5 | 250 |
+--------------+-------+-------+-------+
info
+---------+---------------+------------+
| id | name | gtotal | dated |
+-----+--------+----------+------------+
| 10 | Hari | NULL | 2021-05-15 |
+---------+------------+---------------+
I want to create a trigger through phpmyadmin, as soon as data will be inserted, then info.gtotal will be updated by adding data.total from matched info_id from table name- data.
what will be the trigger if update on data happens too. I just want to create both triggers.
I am new with such, please help me. Any help is accepted.
You need to create two triggers one for insert and another for update.
CREATE TRIGGER `insert_trigger`
AFTER INSERT ON `data`
FOR EACH ROW
UPDATE info
SET gtotal = gtotal + new.total
WHERE id = new.info_id;
Here new.info_id will have the info_id value of newly insert record
CREATE TRIGGER `update_trigger`
AFTER UPDATE ON `data`
FOR EACH ROW
UPDATE info
SET gtotal = (gtotal - old.total) + new.total
WHERE id = new.info_id;
Here old.total will have the total value of record before updating. new.total is the total value after updation.
Since you haven't conveyed what to do after update I have added the logic of subtracting the total from old total and added the new total value. Change it as per your requirement.
You can also create these triggers using GUI in phpmyadmin. You have to select the triggers in the menu bar and add the trigger definition.

mysql insert if not exists doesn't work creating duplicate keys

although i am using mysql "insert ignore" statement
to insert a row to a table called software
i want to make sure that i will not insert a software that already exists in the table.
my table called software and i want to insert
new software to this table but if its already
exists in the table,i want the skip the insert
my table looks like this:
+----+-----------+
| id | name |
+----+-----------+
| 1 | software1 |
| 2 | software2|
| 3 | software3 |
| 4 | software4 |
| |
+----+-----------+
i used "insert ignore" but still its creates duplicate keys
MariaDB [db]> insert ignore into software values (5,'software4');
now i can see that there is a duplicate software4 key
+----+-----------+
| id | name |
+----+-----------+
| 1 | software1 |
| 2 | software2|
| 3 | software3 |
| 4 | software4 |
| 5 software4
+----+-----------+
although i can see similar question here:
mysql insert only if not exists doesn't work
as i am mysql newbie it didn't help me
check: https://mariadb.com/kb/en/library/insert-ignore/
"By using the IGNORE keyword all errors are converted to warnings, which will not stop inserts of additional rows."
If you do not want to have duplicate entries in name, make them UNIQUE:
CREATE TABLE t1 (x int UNIQUE);
First Make the name column unique so you are sure that there are no duplicate entries:
ALTER TABLE software ADD UNIQUE (name);
And then use INSERT IGNORE... which will only INSERT if it still doesn't exist
INSERT INTO software (id, name)
SELECT 4, 'software4'
FROM software
WHERE NOT EXISTS(
SELECT 1 FROM software WHERE name = 'software4'
) LIMIT 1;
DEMO
This will insert the record, only when the name is not already existing.

How to increment a field in MySql using “ON DUPLICATE KEY UPDATE” when each row increment each value?

this question like increment a field with same value
but I want to achieve each row increment each value
for example:
a is a primary key
Original data
a | share_count | read_count |
1 | 2 | 3 |
through
INSERT INTO table (a, share_count,read_count)
VALUES(1,share_count+1,read_count+2),(2,share_count+2,read_count+3)
ON DUPLICATE KEY UPDATE
a=VALUES(a),share_count=VALUES(share_count),read_count=VALUES(read_count)
Goal result
a | share_count | read_count |
1 | 3 | 5 |
2 | 2 | 3 |
I tried,but fail.Thanks for answering
Usually if you try to INSERT you insert count=1 but not share_count+2 or read_count+3.
If I guess your goal correctly you need something like:
http://sqlfiddle.com/#!9/9d4c6/1
INSERT INTO t1 (a, share_count,read_count)
VALUES
(1,1,1),
(2,1,1)
ON DUPLICATE KEY UPDATE
share_count=share_count+1,read_count=read_count+1

Insert If duplicate not found in table else update

I wanted to ignore or update duplicate when I am going to insert values. I know about on duplicate key but i can't figure out the solution with that. Here is sample table example.
| ID | roll | sub | mark |
| ---- |----------| ------|------|
| 1 | 100 | 11 | 15 |
| 2 | 101 | 11 | 16 |
| 3 | 102 | 11 | 17 |
| 4 | 100 | 12 | 10 |
| 5 | 101 | 12 | 11 |
| 6 | 102 | 12 | 12 |
Here the id is primary key but I wanted to insert to check if roll & sub already exist then update otherwise insert new row. I've tried with the following code but that's insert duplicate row but it should update row 6 in following table.
CREATE INDEX mycompo_index on student(roll,sub);
insert into student(roll, mark, sub)
values (102, 22, 12)
on duplicate key update mark = values(mark);
If the combination of roll and sub should be unique, you should define such a key in your table:
ALTER TABLE student ADD CONSTRAINT student_uq UNIQUE(roll, sub)
Note that if you do this, you don't have to explicitly create the index you're creating, the constraint will create on for you. Once you have this is place, you can use the on duplicate key syntax you were trying to use:
INSERT INTO student(roll, mark, sub)
VALUES (102, 22, 12)
ON DUPLICATE KEY UPDATE mark = VALUES(mark)

MySQL Insert or Update (Where 2 columns match)

I have a table structure like below (like dummy data below).
RecordId | UserId | TestId | Score
----------------------------------
1 | 1 | 4 | 98
2 | 1 | 5 | 92
3 | 1 | 6 | 91
4 | 2 | 4 | 99
5 | 2 | 5 | 07
6 | 2 | 6 | 08
I want to update the above but I don't have the RecordId handy.
So lets say UserId 2 on TestId 5 got a Score 55.
We don't currently know wether a record even exists for UserId 2 on TestId 5 so it needs to add the data if it doesn't already exist. If The UserId and TestId do already exist I need to update them.
I don't 'think' i want to use any of the replace queries as I have read that these delete the old record and a create new one, which would have a new Id.
I 'think' it needs to be update with a on duplicate update but i cannot get this to work?
Any help would be much appreciated.
Ok so here is the answer.
Turns out my query was fine but i needed to create a unique key
Here is the prepared SQL statement I used.
INSERT INTO test (UserId, TestId, Score) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE UserId=? TestId=? Score=?;
To make this update when unique combination of UserId & TestId I used the follow SQL query.
ALTER TABLE test ADD UNIQUE KEY `UserTests` (`UserId`, `TestId`);
I hope this & my explanation helps someone out.