获取范围中的下一个可用值

时间:2014-10-24 23:00:32

标签: mysql sql

我有一个包含如下值的表:

"things"
+ FirstOctet + SecondOctet +
| 0          | 0           |
| 0          | 1           |
| 1          | 0           |
| 1          | 0           |
+------------+-------------+

基本上,FirstOctetSecondOctet包含范围为0-255的值。行没有特定的顺序。我想根据最低FirstOctetSecondOctet查询数据库以获取表中的下一个可用值。 FirstOctet和SecondOctet没有重复的值(如果这有意义的话)。

所以,如果表格看起来像:

"things"
+ FirstOctet + SecondOctet +
| 1          | 0           |
| 1          | 4           |
| 1          | 1           |
| 1          | 3           |
+------------+-------------+

我希望找到下一个可用的值为FirstOctet=1SecondOctet=2

到目前为止我只是一个非常简单的查询来计算第一个八位字节,并且计数低于255.

select 
    *, count(*) as count
from
    things
group by first_octet
having count < 255
order by first_octet

我不知道从哪里开始。我一旦发现FirstOctet&lt; 255,它必须有一个可用的行。我从哪里开始?

2 个答案:

答案 0 :(得分:2)

工作演示:http://sqlfiddle.com/#!2/1e60c8/3

CREATE VIEW ViewBoolean AS SELECT 0 as b UNION SELECT 1 as b;
CREATE VIEW ViewByteValues AS
SELECT b0.b + b1.b*2 + b2.b*4 + b3.b*8 + b4.b*16 + b5.b*32 + b6.b*64 + b7.b*128 as v       FROM
ViewBoolean b0,ViewBoolean b1,ViewBoolean b2,ViewBoolean b3,ViewBoolean b4,ViewBoolean b5,ViewBoolean b6,ViewBoolean b7;

-- above from covus corax, http://stackoverflow.com/questions/304461/generate-an-integer-sequence-in-mysql

CREATE VIEW ViewOctetPairs AS
SELECT octet1.v as octet1, octet2.v as octet2
  FROM ViewByteValues AS octet1
CROSS JOIN
      ViewByteValues AS octet2
WHERE octet1.v < 256
AND
octet2.v < 256
;

Create Table things 
(Octet1 INT,
 Octet2 INT)
;

然后查询

SELECT * FROM ViewOctetPairs as allPairs
LEFT JOIN
   things
ON allPairs.octet1 = things.octet1
AND allPairs.octet2 = things.octet2
WHERE things.octet1 IS NULL
ORDER BY allPairs.octet1 ASC, allPairs.octet2 ASC
LIMIT 1

这个想法是 - 你创建一个2列“视图”,每个数字排列。然后你将它与“事物”联系起来,只从“事物”中选择的视图中的行,然后选择第一列,其中first表示最低可用第一列,如果该列中有多个可用的第二列。

答案 1 :(得分:1)

我试试这个:

select FirstOctet, SecondOctet + 1

from things t1

where not exists (select * from things t2 where t1.FirstOctet = t2.FirstOctet and
                   t1.SecondOctet + 1 = t2.SecondOctet)
      and SecondOctet + 1 < 255

order by FirstOctet, SecondOctet

limit 1

Sql fiddle