开发者

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开发者_JS百科 it could, so I though I'd ask: Can I do this in a better way?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜