Jump to content

Mysql query


odinski

Recommended Posts

I'd like to select an unused ID within a given range in my table. E.g. the first unused id available between 18000-19000.

 

I've been using:  select max(id) +1 from source where id between 18000 and 19000;

which eventually have lead to the point where the maximum is used. And prior to this, previous ID's have been deleted, hence I currently have over 500 unused IDs within that range...

 

Is it possible to write a mysql query to find that first unused id between a given range? If so, hints on how to do it would be very much appreciated. Thanks in advance to those who reply.

Link to comment
Share on other sites

Hi

 

Having ranges of autogenerated ids is representing something generally not a good idea.

 

However, if you must then set up a table (called integers here) with a single column (called i here) with 10 rows with the values 0 to 9. Using this you can generate a range of numbers.

 

For example to get every number between 18000 and 18999 inclusive:-

 

SELECT 18000 + (a.i + (b.i * 10) + (c.i * 100)) AS SomeInt FROM `integers` a, `integers` b, `integers` c

 

You can then JOIN that with your table of existing IDs, but using a LEFT OUTER JOIN to bring back a row even when there isn't an existing ID. Use a WHERE clause to discard any where there is a matching ID in existance. And use MIN to get the lowest one.

 

Something like this:-

 

SELECT MIN(SomeInt)
FROM (SELECT 18000 + (a.i + (b.i * 10) + (c.i * 100)) AS SomeInt FROM `integers` a, `integers` b, `integers` c ) Table1
LEFT OUTER JOIN YourDataTable Table2
ON Table1.SomeInt = Table2.Id
WHERE Table2.Id IS NULL

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.