You can use stored procedure to SELECT and DELETE if exists or INSERT. But much easier would just be left the data there and update seen/unseen with ON DUPLICATE KEY UPDATE.
INSERT new row or DELETE old row IF it already exists
-
07-10-2022 - |
سؤال
I need to optimize/implement a MYSQL query wich do the following:
I need to store if an user marked an item as seen, and create a SEEN/UNSEEN button, that delete the correspondent row on the database if already exists (is marked as seen) OR insert a new row if it not (is not marked).
It means, I need a mysql query that do that:
DELETE FROM table WHERE userid = ? AND itemid = ?
or that
INSERT INTO table (userid, itemid) VALUES (?,?)
depending on if the row already exists or not.
I now it's very easy doing it with php and checking the number of rows of a SELECT before INSERT or DELETE but I would like to doing that all the optimized I can.
المحلول
نصائح أخرى
You could use a third column to store an integer, ad use that value as a "toggle" to switch between seen/unseen through an UPSERT query.
Something like:
INSERT INTO table (userid, itemid, seen) VALUES (?,?,0) ON DUPLICATE KEY UPDATE seen = ((seen+1) MOD 2);
The primary key should be formed by userid
and itemid
. The MOD
operator will make it easy and efficient to implement the seen/unseen behaviour you want.
IMHO, that's a wrong idea. The button in UI shouldn't be called "Make seen/unseen". The button in UI must have concrete name, so user will know what he is doing. So, you will need to make SELECT before displaying a button anyway. And button click event algorithm should not be like this:
if not currently_is_seen then mark_as_seen else mark_as_not_seen;
Button algorithm should be like this:
if current_button_name_is_mark_seen then {
if not currently_is_seen then mark_as_seen;
} else {
if currently_is_seen then mark_as_not_seen;
}
(It's ok if under some specific conditions button is named "mark seen" althrough it's already marked seen -- button will just do nothing. It's ok if under some specific conditions button is named "mark unseen" althrough it's already marked unseen -- button will just do nothing. But it's not ok when button titled "mark seen" or "mark unseen" does an opposite action instead.)
To implement
if not currently_is_seen then mark_as_seen;
and
if currently_is_seen then mark_as_not_seen;
you can use
INSERT IGNORE INTO table (userid, itemid) VALUES (?,?)
and
DELETE FROM table WHERE userid = ? AND itemid = ?
(delete doesn't cause error if record doesn't exists).
Hovewer, if you want to implement the
if not currently_is_seen then mark_as_seen else mark_as_not_seen;
logic very much, you can use stored routine (also here).
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); check the following link
http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm