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,其他,先这样吧
相关推荐
睡不醒男孩03082317 分钟前
第二篇:深入探索开源数据库高可用:构建基于CLup的PostgreSQL生产级高可用与读写分离架构
数据库·postgresql·开源·clup
Micro麦可乐3 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
码农阿豪3 小时前
从零到一:Spring Boot快速接入金仓数据库实战
数据库·spring boot·后端
鼎讯信通3 小时前
风电光缆运维提质增效:G-4000A 光缆故障追踪仪破解风场巡检难题
运维·网络·数据库
三十..3 小时前
MySQL 从入门到高可用架构实战精要
运维·数据库·mysql
cfm_29144 小时前
Redis五大基本数据结构底层了解
数据结构·数据库·redis
如竟没有火炬4 小时前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
真实的菜5 小时前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
8Qi85 小时前
LeetCode 1143 & 718:最长公共子序列 / 最长重复子数组
算法·leetcode·职场和发展·动态规划
你想考研啊5 小时前
mysql数据库导出导入
数据库·mysql·oracle