A
A
Andrey Strelkov2020-05-02 00:29:10
MySQL
Andrey Strelkov, 2020-05-02 00:29:10

How to check if an existing row is identical before inserting a new one?

Good afternoon, please tell me if it is possible to put additional logic in INSERT, or do you need separately logic first, and then the action

There is a table

id ; login ; host ; event_id ; date
1; strelkov.av ; home_pc ; 1 ; 11:00:00
2; strelkov.av ; home_pc ; 2 ; 12:00:00
3; strelkov.av ; home_pc ; 3 ; 13:00:00
4; strelkov.av ; home_pc ; 1 ; 14:00:00


Now the command will go

insert into table (login, host, event_id, date) values ('strelkov.av', 'home_pc', '1', now());


And the bottom line is that, in theory, in the context of the login - strelkov.av and the host - home_pc , the last entry in the table already has an event_id, then in this case you need to skip insert and not do it. when inserting a new value, first check for the same login and host data, if the last record has the same event_id as the new one being inserted, then do not insert
if the last record has a different event_id, then you can safely insert a new

record Substitute logic in the request, or it needs to be done separately by a procedure, or on the client side, first check

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2020-05-02
@HeadOnFire

INSERT INTO my_table (login, host, event_id) 
SELECT 'strelkov.av', 'home_pc', 1
FROM my_table
WHERE login='strelkov.av' 
AND host='home_pc'
AND event_id=1
HAVING COUNT(*)=0;

Please note that you need to specify login, host and event_id values ​​in 2 places. It works like this - if the SELECT ... HAVING COUNT(*)=0 construct returns true (that is, SELECT did not find a record with the same login, host, and event ID), then INSERT will be performed. If SELECT returns false (COUNT is not equal to 0, then such a row already exists), then INSERT will be ignored entirely. I understand that this does not immediately get into it, but SQL is an interesting thing :)
PS: It is assumed that your id is AUTO_INCREMENT, while date has DEFAULT NOW () and you don’t need to pass them at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question