如何从ID列中获取所有缺失的数字

时间:2019-10-21 10:39:52

标签: mysql database

Users表在mysql数据库中具有id字段,并且该表在id字段中具有以下记录

| id |

2
3
5
6
9
10
15
16
18
21
25

我想丢失记录,如下所示:-

1
4
7
8
11
12
13
14
17
19
20
22
23
24

2 个答案:

答案 0 :(得分:2)

这有多酷?

SELECT seq.`id` FROM (
SELECT @row := @row + 1 as `id`
FROM `users` t, (SELECT @row := 0) r
CROSS JOIN `users` t2
) as seq WHERE seq.`id` NOT IN (SELECT `id` FROM `users`) 
AND seq.`id` <= (SELECT max(`id`) from `users`);

如果您希望将缺少的ID用于分析目的,应该爱上这个:

SELECT CONCAT(dt.missing, IF(dt.`found`-1 > dt.missing, CONCAT(' to ', dt.`found` - 1), '')) AS missing
FROM ( SELECT @rownum:=@rownum+1 AS `missing`,
    IF (@rownum=id, 0, @rownum:=id) AS `found`
 FROM ( SELECT @rownum:=0 ) AS r
 JOIN users
 ORDER BY id ) AS dt
WHERE dt.`found`!= 0;

答案 1 :(得分:-1)

使用日历表方法和反联接方法:

CREATE TABLE nums (id INT);
INSERT INTO nums (id)
(
    SELECT (t*10+u+1) x FROM
    (SELECT 0 t 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) A,
    (SELECT 0 u 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) B
);

SELECT
    n.id
FROM nums n
LEFT JOIN users u
    ON n.id = u.id
WHERE
    u.id IS NULL
ORDER BY
    n.id;

Demo

请注意,在演示和查询中,我并没有限制返回的缺失数字范围的高度。我任意使用数字序列1..100,但是您可以限制为任意大小。