检测(自动递增)序列中的缺失值 [英] Detect missing values in a (auto-incremented) sequence

查看:89
本文介绍了检测(自动递增)序列中的缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个端口" INT列,其范围应该在30000到50000之间.

因此,我有一个存储过程插入值(端口不为空).因此,我必须手动"选择该字段上存储的值.问题是,我可以在某个点增量地插入(30000,30001,30002 ....),某些条目将被删除(它变成30000、30002、30004 ....),所以要设置孔.

我需要在我的SP中放置一种适合这些孔的方式(在示例中,我的孔为30001,30003 ....).我的问题是,如何在SP中检查某个值是否已被占用".

我以为使用MySQL的LOOP.尝试过这样的事情:

CREATE PROCEDURE teste()
BEGIN
DECLARE p INT;
DECLARE aux INT;
SET p = 30000;

  label1: LOOP

    SELECT Port FROM Reg WHERE Port = p INTO aux;

    IF p = 50000 THEN
    LEAVE label1;
    END IF;


    IF aux IS NULL THEN -- aux-1 is not null, so I can verify the "next  miminum available position"
        aux = aux - 1;
        LEAVE label1;

    ELSE
        SET p = p + 1;
        ITERATE label1;


    END IF;

  END LOOP label1;

 RETURN aux;

END $$

我的问题是获取结果值.如果我放置该RETURN语句,则会得到仅在FUNCTION上允许的信息.当我结束循环时,SELECT的结果始终为空.

我该怎么办?

解决方案

SELECT IFNULL(MIN(r1.Port) + 1, 30000) as minport
FROM Reg r1
LEFT JOIN Reg r2 ON r1.Port + 1 = r2.Port
WHERE r2.Port IS NULL:

I have a 'Port' INT column, which it's supposed to range from 30000 to 50000.

So, I have a Stored Procedure inserting values (Port is NOT NULL). So I have to choose 'manually' the value storing on that field. Problem is, altough I can insert incrementally (30000,30001,30002....) at a certain point some entries are deleted (it becames 30000, 30002, 30004.... ) so there are holes to be set.

I need to place in my SP a way to fit those holes (on the example I have they are 30001,30003 ....). My problem is how to check within the SP, if a certain value is already 'ocuppied'.

The I thought using LOOP from MySQL. Tried something like this:

CREATE PROCEDURE teste()
BEGIN
DECLARE p INT;
DECLARE aux INT;
SET p = 30000;

  label1: LOOP

    SELECT Port FROM Reg WHERE Port = p INTO aux;

    IF p = 50000 THEN
    LEAVE label1;
    END IF;


    IF aux IS NULL THEN -- aux-1 is not null, so I can verify the "next  miminum available position"
        aux = aux - 1;
        LEAVE label1;

    ELSE
        SET p = p + 1;
        ITERATE label1;


    END IF;

  END LOOP label1;

 RETURN aux;

END $$

My problem is obtaining a result value. If I place that RETURN statement I get the info that is only allowed on a FUNCTION. And the result from the SELECT is always null when I end the Loop.

What can I do?

解决方案

SELECT IFNULL(MIN(r1.Port) + 1, 30000) as minport
FROM Reg r1
LEFT JOIN Reg r2 ON r1.Port + 1 = r2.Port
WHERE r2.Port IS NULL:

这篇关于检测(自动递增)序列中的缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆