Skip to content
Advertisement

update a random row and get the row result back in MySQL

I have this table

and an insert command is the following:

The table contains random codes for each product_id. I want to get one unused code randomly (LIMIT 1 is ok for the job), mark the code as used and return it to the next layer.

So far I did this:

but this does not work well when multiple threads request the first unused code. What is the optimal solution to do this query? I would like to avoid stored procedures.

Advertisement

Answer

Possible solution.

Assumes that there aren’t other predefined values stored in used column except 0 and 1.

To prevent indefinite loop (for example when no rows with used=0) add some counter which increments in REPEAT cycle and breaks it after some reasonable iteration attempts.

The code may be converted to FUNCTION which returns selected rowid.

It is possible that the procedure/function fails (by some external reasons), and a row will stay “selected by current CONNECTION_ID()” whereas the connection is broken itself. So you need in service procedure executed by Event Scheduler which will garbage the rows which belongs to non-existed connections and clear their used value back to zero returning such rows to unused pool.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement