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,其他,先这样吧
相关推荐
lueluelue474 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水1687 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
凌虚7 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
五阿哥永琪8 小时前
MySQL中操作json的函数!
数据库·mysql·json
来者皆善8 小时前
了解Mysql优化吗?如何优化索引?
数据库·mysql
赤壁小虾10 小时前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
MC皮蛋侠客10 小时前
SQLAlchemy 系列(七):高级建模与高效写入——批量 DML、方言与扩展
数据库·python
Re.不晚10 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
奈斯先生Vector11 小时前
把 Midjourney 二次编辑做成生产系统:customId 能力令牌、Action Graph 与 WebUI 精修工作台
数据库·人工智能·架构·aigc·音视频·midjourney
青山木11 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode