6

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?

Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109

2 Answers2

1

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

Ashrith
  • 655
  • 8
  • 20
  • Please see this question http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update – Markus Hedlund Oct 15 '13 at 16:01
  • The performance of insert ... on duplicate key update is subjecive. Please read: http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/ – Ashrith Oct 17 '13 at 05:09
1

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

Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109