Skip to content

Latest commit

 

History

History
101 lines (80 loc) · 2.2 KB

File metadata and controls

101 lines (80 loc) · 2.2 KB

English Version

题目描述

表: Customers

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

 

写一个 SQL 语句, 找到所有遗失的顾客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,即可得到结果。

SQL

# 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 ids
from
    t
where
    n < (
        select
            max(customer_id)
        from
            Customers
    )
    and n not in (
        select
            customer_id
        from
            Customers
    )