SQL力扣

今天的题好多case then else end的

608-tree-node

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

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

sql 复制代码
-- 
select id,
       case
           when p_id is null then 'Root'
            when Tree.id in (select p_id from Tree) then 'Inner'
            else 'Leaf'
        end as type
from Tree

错误的答案和原因

sql 复制代码
select
    id,
    case when p_id is null then "Root"
         when id not in (select p_id from tree) then "Leaf"
         else "Inner"
    end as Type
from
    tree

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日 星期五

sql 复制代码
select x, y, z,
       case
           WHEN 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日 星期五

sql 复制代码
select max(t.num) AS num
from (
         select num
         from MyNumbers
         group by num
         having 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日 星期五

sql 复制代码
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日 星期五

sql 复制代码
-- 对于所有座位 id 是奇数的学生,修改其 id 为 id+1,如果最后一个座位 id 也是奇数,则最后一个座位 id 不修改。对于所有座位 id 是偶数的学生,修改其 id 为 id-1。
select (case when mod(id, 2) = 1 and counts != id then id + 1
            when mod(id, 2) = 1 and counts = id then id
        else id-1
        end) as id,
       student
from seat,
     (select count(*) as counts from seat) as seat_counts
order by id asc
相关推荐
S1998_1997111609•X4 小时前
论当今社会主义与人文关怀人格思想下的恶意仿生注入污染蜜罐描述进行函数值非法侵入爬虫的咼忄乂癿〇仺⺋.
数据库·网络协议·百度·ssh·开闭原则
倔强的石头_5 小时前
kingbase备份与恢复实战(六)—— 备份自动化与保留策略:Windows任务计划+日志追溯
数据库
轻刀快马5 小时前
别被 ORM 框架宠坏了:从一场“订单消失”悬案,看懂 MySQL 为什么要强推 InnoDB
数据库·mysql
浅念-5 小时前
刷穿LeetCode:BFS 解决 Flood Fill 算法
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
学网安的肆伍6 小时前
【043-WEB攻防篇】PHP应用&SQL注入&符号拼接&请求方法&HTTP头&JSON&编码类
sql·安全·php
后端漫漫7 小时前
Redis 客户端工具体系
数据库·redis·缓存
PaperData8 小时前
1988-2025年《中国人口和就业统计年鉴》全年份excel+PDF
数据库·人工智能·数据分析·经管
im_AMBER8 小时前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵
星河耀银海9 小时前
C语言与数据库交互:SQLite实战与数据持久化
c语言·数据库·sqlite·交互
过期动态9 小时前
MySQL中的约束
android·java·数据库·spring boot·mysql