开发者

Mysql non-sequential insert problem

开发者 https://www.devze.com 2023-02-26 06:00 出处:网络
I have a table with 100,000 records described as: ID primary unique int (5) Ticket unique int (5) user varchar (20)

I have a table with 100,000 records described as:

ID primary unique int (5)
Ticket unique int (5)
user varchar (20)

Only fields populated on that table are the first two, ID and Ticket. I need to now assign a user to that ticket when requested. How can i do this? How can I find where the next null user is on the table?

Edit: Explaining Scenario as requested

Its a lottery system of sorts. The Ticket numbers have already been made and populate开发者_JAVA百科d into the table. Now when a user signs up for a ticket, their username has to be inserted next to the next available ticket, in the user field. Im sure theres a much simpler way to do this by inserting the ticket with all the information on a new table, but this is th exact requirement as dumb as it sounds.

So how can I find out where the next null user is on the table?


What is the sorting scheme of the table ?

If the Id numbers are sequential this should work:

SELECT ID FROM TABLE WHERE user is null ORDER by ID LIMIT 1

If Id numbers are NON sequential and you are OK with using the natural sort of the table (sorted as they were entered)

SELECT ID FROM TABLE WHERE user is null LIMIT 1


Find the next NULL row by doing:

SELECT ID 
FROM Ticket
WHERE user IS NULL 
LIMIT 1;

When you update though you'll have to be careful you don't have a race condition with another process also getting the same ID. You could prevent this duplicate allocation problem by having a separate table holding the TicketAllocation, and giving it a unique foreign key constraint pointing back to the Ticket table.


you can also do it in a single query:

UPDATE users SET user = [username] where id = 
(select min(id) from users where user is null) 


This assumes ID is auto-incremented.

Start by finding the first record where the user field is null:

Select * from users where user is null order by id asc limit 1;

Then fill it in:

Update users set user = [username] where id = [id from select];
0

精彩评论

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