584. 寻找用户推荐人
584. 寻找用户推荐人
题目
Table: Customer
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+In SQL, id is the primary key column for this table.
Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them.
Find the names of the customer that are not referred by the customer with id = 2.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Customer table:
+----+------+------------+ | id | name | referee_id | +----+------+------------+ | 1 | Will | null | | 2 | Jane | null | | 3 | Alex | 2 | | 4 | Bill | null | | 5 | Zack | 1 | | 6 | Mark | 2 | +----+------+------------+Output:
+------+ | name | +------+ | Will | | Jane | | Bill | | Zack | +------+
题目大意
表: Customer
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+在 SQL 中,id 是该表的主键列。
该表的每一行表示一个客户的 id、姓名以及推荐他们的客户的 id。
找出那些 没有被 id = 2 的客户 推荐 的客户的姓名。
以 任意顺序 返回结果表。
结果格式如下所示。
示例 1:
输入:
Customer 表:
+----+------+------------+ | id | name | referee_id | +----+------+------------+ | 1 | Will | null | | 2 | Jane | null | | 3 | Alex | 2 | | 4 | Bill | null | | 5 | Zack | 1 | | 6 | Mark | 2 | +----+------+------------+输出:
+------+ | name | +------+ | Will | | Jane | | Bill | | Zack | +------+
解题思路
返回字段:
使用SELECT指定要返回的字段为name(客户姓名)。从Customer表中提取数据。筛选条件:
- 使用
WHERE子句指定筛选条件。 - 包含两种情况:
referee_id为NULL,使用IS NULL判断空值。referee_id不等于2,使用!= 2判断。
- 使用
OR运算符将上述条件结合,确保筛选出的客户符合任意一个条件。
- 使用
复杂度分析
- 时间复杂度:
O(n),其中n是Customer表的记录数。SQL 引擎会逐行检查referee_id是否满足条件。 - 空间复杂度:
O(1),无需额外空间,筛选操作在原表上完成。
代码
SELECT name
FROM Customer
WHERE referee_id IS NULL OR referee_id != 2
