Вопрос

email_address
-------------
id
prefix
fqdn

Prefix and fqdn together form a unique key.

I would like to write a query which would do an insert, if the email address is not yet in the table. If the address is already in the table, it should return the id.

Is there a way of writing a query which behaves like INSERT INTO email_address(prefix, fqdn) VALUES (?, ?) ON DUPLICATE SELECT id as LAST_INSERT_ID WHERE prefix = ? AND fqdn = ? would if it were legal?

Basically I want to do an INSERT or SELECT in one query.

Это было полезно?

Решение

If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row instead, LAST_INSERT_ID() is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr). Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;

From http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top