SQL刷题记录
最近期末周在复习数据库概述,顺便练练力扣上的sql题目
以下皆出自力扣高频SQL50题

25.12.20
1757
简单查询,"又"用"and"连接
sql
select product_id
from Products
where low_fats = 'Y' and recyclable = 'Y'
584
也是简单查询,"和"用"or"连接
sql
select name
from Customer
where referee_id != 2 or referee_id is null;
注:
id != 2不包括id是null的因为 :在 SQL 中,任何与
NULL的比较(包括=,!=,<,>,<>等)结果都是UNKNOWN(既不是TRUE也不是FALSE) ,而WHERE子句只保留结果为TRUE的行
620
聚合函数+排序
- 求id为奇数:
id%2 = 1 - 按rating降序排序:
order by rating desc
sql
select *
from cinema
where description != 'boring' and id%2 = 1
order by rating desc;
570
连接
两种方法:
1.子查询
sql
select a.name
from Employee a
where (select count(b.id)
from Employee b
where b.managerId = a.id) >= 5;
注:
COUNT()不能直接包裹一个子查询作为参数
COUNT()是一个聚合函数,它的参数应该是:
- 列名(如
COUNT(b.id))- 表达式(如
COUNT(*))- 或在子查询中使用(但不是这样用)
2.分组查询
sql
select a.name
from Employee a
join Employee b on b.managerId = a.id
group by a.id
having count(a.id) >= 5;
法二比法一更省时,因为:
| 方法 | 执行模型 | 类比 |
|---|---|---|
| 方法二(JOIN + GROUP BY) | 基于集合(Set-based) | 一次性把所有数据"摊开",分组统计,一次完成 |
| 方法一(相关子查询) | 逐行循环(Row-by-row / N+1) | 对主表每一行,都去查一遍子表 |
1193
聚合函数
sql
select DATE_FORMAT(trans_date,'%Y-%m') as month,country,
count(*) as trans_count,
count(if(state = 'approved',1,null)) as approved_count,
sum(amount) as trans_total_amount,
sum(if(state = 'approved',amount,0)) as approved_total_amount
from Transactions
group by month,country;
-
查找每个月和每个国家:
先把年月日转换为年月
DATE_FORMAT(trans_date, '%Y-%m')是 MySQL 中用于格式化日期/时间的函数,它的作用是:
将
trans_date字段的值转换为'年-月'格式的字符串,例如'2025-12'。再在sql语句随后加上
group by mouth,country进行分组 -
查找总事务数:
count(*)再起个别名trans_count -
查找总金额数:
SUM(amount)再起个别名trans_total_amount -
查找已批准的事务数:
count(IF(state = 'approved', 1, NULL)) AS approved_countcount只记录不是null的值,所以如果state不是approved,就置为null即可 -
查找已批准的事物的总金额:
sum(IF(state = 'approved', amount, 0)) AS approved_total_amount已批准就累加
amount
剩下的明后天继续写