Search code examples
mysqlsqlminimum

Find minimum non-used value from collection of rows marked with an id and customId


I already saw a similar question here(Get minimum unused value in MySQL column) which is exactly what I want except what I need to select the minimum available number not from just a table but from rows with specific customId as well. In case the other question gets removed or something, here is what query is needed:

In case of rows [1,2,3] the query should return 4.

In case of rows [2,3,4] the query should return 1.

In case of rows [1,3,4] the query should return 2.

In case of multiple missing rows [1,2,4,6,7] the query should return minimum missing value 3.

I tried solutions showed in the first linked question and from this one as well link(SQL - Find the lowest unused number). I tried tweaking them to include customId in WHERE clauses but the queries is too advanced and confusing for me, so it did not work. I have tried doing this:

  SELECT min(unused) AS unused
  FROM (
  SELECT MIN(t1.id)+1 as unused
  FROM yourTable AS t1
  WHERE t1.customId = ? AND NOT EXISTS (SELECT * FROM yourTable AS t2 WHERE t2.customId = ? 
   AND t2.id = t1.id+1)
  UNION
  -- Special case for missing the first row
  SELECT 1
  FROM DUAL
    WHERE customId = ? AND NOT EXISTS (SELECT * FROM yourTable WHERE id = 1)

  )AS subquery

But it shows access or syntax violation error.


Solution

  • I tweaked one of the queries I found on the web until it worked... Obviously it is not neccesarily fast or perfomant but it work, so here it goes:

    SELECT min(unused) AS unused FROM
      ( SELECT MIN(t1.group_number)+1 as unused FROM units AS t1 WHERE t1.user_id = '.$ai_id.' AND 
         NOT EXISTS (SELECT * FROM units AS t2 WHERE t2.user_id = '.$ai_id.' AND t2.group_number= 
       t1.group_number +1) UNION
        -- Special case for missing the first row 
        SELECT 1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM units  WHERE  group_number= 1 
        AND user_id = '.$ai_id.') )AS subquery
    

    I am not sure how exactly it works, but it somehow does, I can only get the outlines... The user_id in this case is the aforementioned customId and unit_group_number is the column used to search for missing "hole" value which will be returned as unused.