SQL-leetcode-584. 寻找用户推荐人

584. 寻找用户推荐人

表: 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 |

±-----+

题解

找出那些 没有被 id = 2 的客户 推荐 的客户的姓名。

where 就行,但要考虑一点就是没有推荐人的情况,null是不能用来比较的

方法一 where

复制代码
select name from Customer where referee_id <> 2 or referee_id is null

方法二 where + ifnull

复制代码
select name from Customer where ifnull(referee_id,0) <> 2

方法三 exists

逆向思维,把推荐人是2的拿出来,通过not exists来实现

复制代码
-- 判断c1 表的数据,不存在c2白哦中
select name from Customer c1 where 
not exists(
    select name from (
    select * from Customer where referee_id = 2
) c2 
where c1.id = c2.id
-- where c1.referee_id = c2.referee_id
)
emmm,其他,先这样吧
相关推荐
等....1 小时前
Minio使用
数据库
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
win x2 小时前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
迷枫7123 小时前
DM8 数据库安装实战:从零搭建达梦数据库环境(附全套工具链接)
数据库
XDHCOM3 小时前
PostgreSQL 25001: active_sql_transaction 报错原因分析,故障修复步骤详解,远程处理解决方案
数据库·sql·postgresql
Morwit4 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
py有趣4 小时前
力扣热门100题之岛屿的数量(DFS/BFS经典题)
leetcode·深度优先·宽度优先
卤炖阑尾炎4 小时前
PostgreSQL 日常运维全指南:从基础操作到备份恢复
运维·数据库·postgresql
daad7775 小时前
wifi_note
运维·服务器·数据库
qinian_ztc5 小时前
frida 14.2.18 安装报错解决
算法·leetcode·职场和发展