当前位置: 首页 > news >正文

SQL力扣

今天的题好多case then else end的

608-tree-node

https://leetcode.com/problems/tree-node/description/

树节点,流控制语句CASE,2025年6月13日 星期五

-- 
select id,casewhen p_id is null then 'Root'when Tree.id in (select p_id from Tree) then 'Inner'else 'Leaf'end as type
from Tree

错误的答案和原因

selectid,case when p_id is null then "Root"when id not in (select p_id from tree) then "Leaf"else "Inner"end as Type
fromtree

A not in B的原理是拿A表值与B表值做是否不等的比较, 也就是a != b. 在sql中, null是缺失未知值而不是空值(详情请见MySQL reference).

当你判断任意值a != null时, 官方说, “You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL”, 任何与null值的对比都将返回null. 因此返回结果为否,这点可以用代码 select if(1 = null, ‘true’, ‘false’)证实.

从上述原理可见, 当询问 id not in (select p_id from tree)时, 因为p_id有null值, 返回结果全为false, 于是跳到else的结果, 返回值为inner. 所以在答案中,leaf结果从未彰显,全被inner取代.

610-triangle-judgement

https://leetcode.com/problems/triangle-judgement/

case then else,2025年6月13日 星期五

select x, y, z,caseWHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes'else 'No'end as 'triangle'
from Triangle

619-biggest-single-number

https://leetcode.com/problems/biggest-single-number/description/

单一数字 是在 MyNumbers 表中只出现一次的数字。

找出最大的 单一数字 。如果不存在 单一数字 ,则返回 null 。

只出现一次的最大数字,2025年6月13日 星期五

select max(t.num) AS num
from (select numfrom MyNumbersgroup by numhaving count(num) = 1) t

620-not-boring-movies

https://leetcode.com/problems/not-boring-movies/description/

发现自己容易把SQL和Python混淆,这里的mod,写成了%2 == 1

mod(id, 2) = 1,2025年6月13日 星期五

select id, movie, description, rating
from cinema
where mod(id, 2) = 1 and description != 'boring'
order by rating desc

626-exchange-seats

https://leetcode.com/problems/exchange-seats/description/

交换位置,2025年6月13日 星期五

-- 对于所有座位 id 是奇数的学生,修改其 id 为 id+1,如果最后一个座位 id 也是奇数,则最后一个座位 id 不修改。对于所有座位 id 是偶数的学生,修改其 id 为 id-1。
select (case when mod(id, 2) = 1 and counts != id then id + 1when mod(id, 2) = 1 and counts = id then idelse id-1end) as id,student
from seat,(select count(*) as counts from seat) as seat_counts
order by id asc
http://www.xdnf.cn/news/1016605.html

相关文章:

  • 【AI News | 20250613】每日AI进展
  • 使用若依框架新建模块后导入UI项目目录对应前端文件后报找不到文件错误处理
  • 【DVWA系列】——xss(Stored)——High详细教程
  • 高精度算法详解:从原理到加减乘除的完整实现
  • 【AI图像生成网站Golang】部署图像生成服务(阿里云ACK+GPU实例)
  • skynet源码学习-skynet_mq队列
  • 目标检测标注格式
  • 对象映射 C# 中 Mapster 和 AutoMapper 的比较
  • 无人机侦测与反制技术进展
  • 精益数据分析(101/126):SaaS商业模式优化与用户生命周期价值提升策略
  • React 第六十一节 Router 中 createMemoryRouter的使用详解及案例注意事项
  • 【CSS-12】掌握CSS列表样式:从基础到高级技巧
  • 如何快速搭建门店系统?
  • 浅析MySQL数据迁移与恢复:从SQLServer转型到MySQL
  • 搭建网站应该怎样选择服务器?
  • 在mac上安装sh脚本文件
  • C++标准库大全(STL)
  • Spring Boot 集成国内AI,包含文心一言、通义千问和讯飞星火平台实战教程
  • 域名+nginx反向代理实现案例
  • Python学习笔记:错误和异常处理
  • 影像组学5:Radiomics Score的计算
  • 深度学习驱动的验证码识别实战:从原理到高并发工业部署
  • YOLOV11改进之多尺度扩张残差模块(MS-DRM)
  • [特殊字符][特殊字符] Harmony OS Next玩转多层级手势事件:当组件遇上“套娃”,触摸该怎么分家?
  • 北斗导航 | 基于matlab的卫星导航单点定位算法
  • Linux文件权限详解:从入门到精通
  • 每日Prompt:Steve Winter风格插画
  • 2.3 ASPICE的架构与设计
  • 服务器上安装配置vsftpd
  • Java流处理中的常见错误与最佳实践