开发者

Can I add an entry to mysql and return a column if it's not present in one query?

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 que开发者_运维知识库ries (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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜