开发者

Select numbers that are not in a column

开发者 https://www.devze.com 2023-03-31 20:35 出处:网络
I have a column of type integer and the records has 开发者_JAVA技巧numbers from 1 to 270 so far. I\'d like to write a query that returns numbers that are not in the database between 1 and 270.

I have a column of type integer and the records has 开发者_JAVA技巧numbers from 1 to 270 so far. I'd like to write a query that returns numbers that are not in the database between 1 and 270. e.g. number 5, 10, 15, 117 are missing. So that query should return these numbers. And there are some numbers missing because the count of records is less than 270 and it's unpractical to search it with eye.

thank you


Do a self join to find consecutive numbers, and where there is no match, you have a missing number.

SELECT t1.i-1 AS missing_i
FROM thetable t1 LEFT OUTER JOIN thetable t2 ON t1.i-1 = t2.i
WHERE t2.i IS NULL

But this doesn't find all missing numbers, only the ones that are one less than a number that is present. If all your gaps are only one number, this is okay. But if you have gaps that are sequences of two or more numbers, you may have to use an alternative technique:

Create a table and fill it with integers at least 1 to 270:

CREATE TABLE n (i INT AUTO_INCREMENT PRIMARY KEY, dummy INT);
INSERT INTO n (dummy) VALUES (0);          -- now you have 1 row
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 2 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 4 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 8 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 16 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 32 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 64 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 128 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 256 rows
INSERT INTO n (dummy) SELECT dummy FROM n; -- now you have 512 rows

Now you can do an outer join to search for those integers missing in your original table:

SELECT n.i AS missing_i
FROM n LEFT OUTER JOIN thetable t ON n.i = t.i
WHERE n.i <= 270 AND t.i IS NULL
0

精彩评论

暂无评论...
验证码 换一张
取 消