How to insert a record into a table only if that row (key;value) yet?

When you insert you need to check whether there is any row in the table.
Don't want to add a separate query to check first experience with the database, but I assume that it will increase the load.
Suggested that it is possible to use a composite unique key, but can't understand the documentation
INSERT INTO dialogs (dialog_id, user_id) VALUES (1, 101)
how to modify that checked whether the string dialog_id=1 and user_id=101?
Maybe I do not at all, tell me please, who knows how to be in this situation?
March 19th 20 at 08:38
1 answer
March 19th 20 at 08:40
Add UNIQUE dialog_id, user_id
INSERT IGNORE INTO dialogs (dialog_id, user_id) VALUES (1, user_1)
thank you) - casey23 commented on March 19th 20 at 08:43
so it's Vice versa will ignore a double UNIQUE index.
And the author, on the contrary it is necessary to not inserted.
What the author and so everything is OK - he has a UNIQUE key on these two fields created, when adding a brace will be error Duplicate entry '1-101' for key 'dialog_id'.

However it would be nice adequate to give the name of the double index - no dialog_id, what is the name of one of the speakers, and "dublicate_dialog_user".

Either I do not understand the question. - Kelsie_Pour commented on March 19th 20 at 08:46
@Kelsie_Pourif you use the IGNORE Duplicate entry '1-101' for key 'dialog_id' will not just ignore and all. The entry will not be added - Clinton.Donnelly commented on March 19th 20 at 08:49
@Kelsie_Pour, that's right, the error was previously proposed code works like as it should, except, is it normal that I have id(pk) increases, if the row was not added? - casey23 commented on March 19th 20 at 08:52
@casey23, Yes, this is normal in MySQL.


man shows a crutch to avoid it.
But what is stopping you from growth?

If you at some point you will need to determine the total number, because you want a normal auto_increment from ID, just use COUNT(id) when calculating the total. - Kelsie_Pour commented on March 19th 20 at 08:55
@Kelsie_Pour, thank you very much for the link) does not bother me, I just wanted to check, just had the opportunity) good day to All! - casey23 commented on March 19th 20 at 08:58
a lot of things done and only realized that until now have not received dialog_id using the list of user IDs in it including. Prompt what method it's done?
Gives Google GROUP BY... HAVING COUNT again, apparently not.
5c9a505dd3721324189700.png - casey23 commented on March 19th 20 at 09:01

Find more questions by tags MySQL