我有一个这样的MySQL表:
+--------+-------+
| Server | Port |
+--------+-------+
| 1 | 27001 |
| 2 | 27002 |
| 4 | 27004 |
+--------+-------+你可以看到-这里是27003端口-但它在一段时间前被删除了(只是举个例子)。
有没有办法知道mysql表中不使用的最小值(比如大于27000 )?或者没有办法,我需要制作一个单独的表,其中包含所有端口和“已使用”或“未使用”的列?
场景说明:我正在创建游戏托管网站,我可以对端口使用自动增量,但一段时间后我会有很多删除/未使用的端口,我想在增加端口范围之前将它们全部使用。
发布于 2011-06-24 15:35:35
在谷歌上快速搜索"first missing number from sequence mysql“,就会得到this page of common MySQL queries。
它向您展示了如何find the first missing number from a sequence
您有一个具有值(1,2,4,18,19,20,21)的表tbl(id int),并且您希望找到其id值序列中缺少的第一个数字:
SELECT t1.id+1 AS Missing
FROM tbl AS t1
LEFT JOIN tbl AS t2 ON t1.id+1 = t2.id
WHERE t2.id IS NULL
ORDER BY t1.id LIMIT 1;
+---------+
| Missing |
+---------+
| 3 |
+---------+ 发布于 2018-07-23 05:24:15
我很高兴这个问题在2011年得到了回答--从MySQL 5.7开始,这似乎更具可读性,并且(根据15M行的表上的解释)比左连接解决方案更快:
select min(id+1) from tbl
where id+1 not in (select id from tbl)请注意,上面的代码也会得到max(id)+1,但您可以在几乎没有额外成本的情况下将其排除:
select min(id+1) from tbl
where id+1 not in (select id from tbl)
and id < (select max(id) from tbl)https://stackoverflow.com/questions/6464656
复制相似问题