tags:

views:

47

answers:

2

Can I have one query to check if an entry is in a mysql table, and if it is present, return a column, but if it's not present, insert it and return a value? I have a users table with the following layout:

userID - int, auto-increment
userName - varchar(100)
active - tinyint(1)

I want to do something like

select userID from users where userName='<some value>'

and if the userName exists, then return the userID, if not, insert it and return the newly incremented userID.

I know I can do this in two queries (one to check if userName exists, then another one to insert), but can I do it in one? I could create a stored procedure to only have one thing to call from my code, but the only way I can envision that stored procedure is to also do the two queries.

I see things like REPLACE INTO and ON DUPLICATE KEY UPDATE, but these only seem to work on updates, not on selecting a value.

+1  A: 

You can check if it exists and insert it in one query:

insert into users (userName) values ('<some value>')
where not exists (
    select * from users where userName = '<some value>'
)

But after that you'll still need to select the userid:

select userid from users where userName = '<some value>'

I don't think an INSERT can be inside a SELECT.

Andomar
actually if userid is the PK on the table, you can get it back all at once using mysql_insert_id()
Zak
http://us3.php.net/mysql_insert_id
Zak
@Zak: That wouldn't work if the user already existed
Andomar
A: 

It should be possible to create a stored procedure that will do this for you, though many people I know would argue against this type of logic existing on the database.

Sonny Boy
But wouldn't the stored procedure still have to do two transactions?
David Buckley