所以,我有一张包含一些独特数字的表格。
假设范围是1到1000。
我想做一个选择查询,获取给定范围内的最低空闲数。
所以,例如:where number > 10 and number < 200
。如果此范围内没有数字,我想返回10
。
如果恰好在此范围内有数字11,12,13, 15, 16
。我想返回14
。
我正在尝试类似下面的内容,但无济于事。
SELECT MIN(number)
FROM
(SELECT 10 number
UNION
SELECT number+1 FROM table) a
WHERE number < 200 AND number
NOT IN (SELECT number FROM table);
感谢。
答案 0 :(得分:2)
SELECT IFNULL(MIN(t1.n) + 1, 10)
FROM (SELECT n
FROM t
WHERE n > 10 # lower bound, exclusive
AND n < 199 # upper bound, inclusive
UNION ALL
SELECT 10) t1
LEFT JOIN t t2
ON t2.n = t1.n + 1
WHERE t2.n IS NULL;
答案 1 :(得分:1)
生成一系列数字(在本例中为1到1000)并将LEFT JOIN加入到您的表中并找到不匹配的数字。使用MIN从表中找不到的生成范围中获取最小数字。
SELECT MIN(iNum)
FROM
(
SELECT 1 + units.i + tens.i * 10 + hundreds.i * 100 AS iNum
FROM (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)units
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)tens
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)hundreds
) a
LEFT OUTER JOIN table b
ON a.iNum = b.number
WHERE a.iNum BETWEEN 10 AND 200
AND b.number IS NULL