mysql - Insert and select the id of a unique element in one query -


i have simple table this

create table authid(   id      int not null auto_increment,   authid  varchar(128) not null unique,   primary key(id) ); 

now if insert value with

insert authid(authid) values('test'); 

it work fine , return inserted id first time, if again when authid exists (notice have authid marked unique) return error.

is there way achieve this in 1 sql statement: insert it, id , if exists, still id.

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

if you're using mysql 5.0 or higher can use "insert ... on duplicate key update" syntax. may able combine last_insert_id() (i'm not positive that)

so:

insert authid (authid) values ('test') on duplicate key update id=last_insert_id(id), authid='test'; select last_insert_id(); 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -