Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to insert, if not exist, then get id in MySQL

There's this table.

| id | domain |

id is the primary key. domain is a unique key.

I want to:

  1. Insert a new domain, if it doesn't exist already.
  2. Get the id for that domain.

Now I'm doing it like this:

INSERT INTO domains
SET domain = 'exemple.com'
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)

Then PDO::lastInsertId() to get the id.

But it's critical that this is as fast as it could, so I though I'd ask: Can I do this in a better way?

like image 289
Znarkus Avatar asked Mar 05 '11 10:03

Znarkus


People also ask

How can I speed up my insert query?

You can use the following methods to speed up inserts: If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.


2 Answers

Until someone says otherwise, I'm saying No, that's the best way.

like image 191
Znarkus Avatar answered Oct 09 '22 19:10

Znarkus


This method has a side effect: "The auto increment id increments by one each time the duplicate key is found".
When the query is run with exemple.com as the value first time it creates the entry. Lets say you repeat that query 13 more times. After that you try with xyz.com you will be surprised to see that instead of auto increment id=2 you get 15.

1 exemple.com
15 xyz.com
25 pqr.com
50 thg.com

like image 23
Ashrith Avatar answered Oct 09 '22 19:10

Ashrith