Skip to content

Latest commit

 

History

History
112 lines (86 loc) · 2.47 KB

File metadata and controls

112 lines (86 loc) · 2.47 KB
comments difficulty edit_url tags
true
中等
数据库

English Version

题目描述

表: Customers

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
+---------------+---------+
customer_id 是该表主键.
该表第一行包含了顾客的名字和 id.

 

编写一个解决方案, 找到所有遗失的顾客 id。遗失的顾客 id 是指那些不在 Customers 表中, 值却处于 1 和表中 最大 customer_id 之间的 id.

注意: 最大的 customer_id 值不会超过 100.

返回结果按 ids 升序 排列

查询结果格式如下例所示。

 

示例 1:

输入:
Customers 表:
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 1           | Alice         |
| 4           | Bob           |
| 5           | Charlie       |
+-------------+---------------+
输出:
+-----+
| ids |
+-----+
| 2   |
| 3   |
+-----+
解释:
表中最大的 customer_id 是 5, 所以在范围 [1,5] 内, ID2 和 3 从表中遗失.

解法

方法一:递归

利用 recursive 关键字,递归生成 [1, 100] 的序列,然后排除已有的 customer_id,即可得到结果。

MySQL

# Write your MySQL query statement below
WITH RECURSIVE
    t AS (
        SELECT
            1 AS n
        UNION ALL
        SELECT
            n + 1
        FROM t
        WHERE n < 100
    )
SELECT
    n AS ids
FROM t
WHERE
    n < (
        SELECT
            MAX(customer_id)
        FROM Customers
    )
    AND n NOT IN (
        SELECT
            customer_id
        FROM Customers
    );