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 小时前
Redis 主从复制详解:原理、配置与主从切换实战
数据库·redis·bootstrap
程序员的世界你不懂2 小时前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
自学也学好编程3 小时前
【数据库】Redis详解:内存数据库与缓存之王
数据库·redis
JAVA不会写3 小时前
在Mybatis plus中如何使用自定义Sql
数据库·sql
IT 小阿姨(数据库)3 小时前
PgSQL监控死元组和自动清理状态的SQL语句执行报错ERROR: division by zero原因分析和解决方法
linux·运维·数据库·sql·postgresql·centos
ChinaRainbowSea4 小时前
7. LangChain4j + 记忆缓存详细说明
java·数据库·redis·后端·缓存·langchain·ai编程
小欣加油4 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream4 小时前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
小马学嵌入式~5 小时前
嵌入式 SQLite 数据库开发笔记
linux·c语言·数据库·笔记·sql·学习·sqlite
Java小白程序员5 小时前
MyBatis基础到高级实践:全方位指南(中)
数据库·mybatis