sql - Problem with MySql INSERT MAX()+1 -


I have a table with many users in that table, I have a column called user_id (INT), which I I want to pay a separate salary for User_id should start with 1

I have prepared a simple example:

  Showing all names ------------- - + - ---------------------- + | User_id | Name | + -------------- + ----------------------- + | 1 | Bob | | 1 | Marriage | | 2 | Bob | | 1 | John | | 3 | Bob | | 2 | Marriage | + -------------- + ----------------------- + Showing only where name = Bob + - - ----------- + ----------------------- + | User_id | Name | + -------------- + ----------------------- + | 1 | Bob | | 2 | Bob | | 3 | Bob | + -------------- + ----------------------- +  

The following questions will do this, but this only works if 'Bob' is already present in the table ...

  Log in user (user_id, name) SELECT (SELECT MAX ( User_id) +1 from users where name = 'bob'), 'bob';  

If Bob is not present (first entry) user_id 0 (zero) is set to the same problem. I need user_id to start with 1_ 0.

You can use something like this:

  Log in user (user_id, name) Select + 1 code (maximum number (user_id) from where user name = 'bob'), 0), 'bob';  

But such a query may have a running position. Make sure you are in the transaction and you lock the user table before running it. Otherwise you may end up with two Bobs with the same number.


Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -