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,其他,先这样吧
相关推荐
sunshine8852 小时前
财务RPA的深水区应用:超越自动化,迈向智能决策支持
数据库
efir OONA2 小时前
MySQL数据库误删恢复_mysql 数据 误删
数据库·mysql·adb
zhangchaoxies3 小时前
如何在 Go 中安全复制接口指针所指向的值
jvm·数据库·python
陈陈CHENCHEN3 小时前
【数据库】MySQL 8.0.40 至 8.0.44 RPM 方式升级指南
数据库·mysql
6Hzlia4 小时前
【Hot 100 刷题计划】 LeetCode 199. 二叉树的右视图 | C++ DFS 逆序遍历
c++·leetcode·深度优先
m0_734949794 小时前
怎么利用Navicat进行调整备份文件压缩等级_详细配置与操作步骤
jvm·数据库·python
T.i.s4 小时前
番外续2-MIT-BIH Arrhythmia Database
数据库
有味道的男人4 小时前
AI 效率翻倍:对接 1688 拍立淘接口,商品全量信息一键抓取
数据库
m0_741173335 小时前
如何处理SQL中的NULL值_使用ISNULL或COALESCE函数
jvm·数据库·python
志栋智能5 小时前
超自动化巡检:解锁运维数据的深层价值
运维·服务器·数据库·自动化