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 andINSERT ... UPDATE
inserts a row, theLAST_INSERT_ID()
function returns theAUTO_INCREMENT
value. If the statement updates a row instead,LAST_INSERT_ID()
is not meaningful. However, you can work around this by usingLAST_INSERT_ID(expr)
. Suppose that id is theAUTO_INCREMENT
column. To makeLAST_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