从标有id和customId的行集合中查找最小未使用值

时间:2018-07-31 10:22:27

标签: mysql sql minimum

我已经在这里(Get minimum unused value in MySQL column)看到了一个类似的问题,这正是我想要的,除了我需要从表中而是从具有特定customId的行中选择最小可用数字。 如果其他问题被删除或其他原因,则需要执行以下查询:

对于第[1,2,3]行,查询应返回 4

对于第[2,3,4]行,查询应返回 1

对于第[1,3,4]行,查询应返回 2

如果有多个缺失行[1,2,4,6,7],则查询应返回最小缺失值 3

我尝试了第一个链接问题中显示的解决方案,也尝试了这个链接(SQL - Find the lowest unused number)。我尝试调整它们以在WHERE子句中包含customId,但是查询对我来说太高级且令人困惑,因此它不起作用。我尝试这样做:

  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

但是它显示访问或语法冲突错误。

2 个答案:

答案 0 :(得分:1)

您可以这样做:

select 1 + min(col)
from t
where not exists (select 1 from t t2 where t2.col = t.col + 1);

如果您需要包含“ 1”,则:

select (case when min(tt.mincol) <> 1 then 1
             else 1 + min(col)
        end)
from t cross join
     (select min(col) as mincol from t) tt
where not exists (select 1 from t t2 where t2.col = t.col + 1)

答案 1 :(得分:0)

我调整了我在网络上找到的一个查询,直到它起作用为止...显然,它不是必需的速度或性能,但是它可以正常工作,所以在这里:

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

我不确定它的工作原理,但是以某种方式起作用,我只能得到轮廓... 在这种情况下,user_id是前面提到的customId,而unit_group_number是用于搜索缺失的“空”值的列,该值将以unused的形式返回。