SQL笔记-2024/01/31

cross join

两个表的笛卡尔积

例如:

select s.name student_name,s.age student_age,s.class_id class_id,c.name class_name

from student s

cross join class c;

子查询

select s.name name,s.score score,s.class_id class_id

from student s

where s.class_id in (select distinct c.id from class c);

子查询 - exists

select s.name,s.age,s.class_id

from student s

where 1=1

and not exists (select 1 from class c where c.id = s.class_id);

组合查询

union 不保留重复行

union all 保留重复行

select s.name,s.age,s.score,s.class_id

from student s

union all

select sn.name,sn.age,sn.score,sn.class_id

from student_new sn;

开窗函数 - sum over

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,AVG(score) over (partition by class_id) as class_avg_score

from student s;

开窗函数 - sum over order by

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,SUM(score) over (partition by class_id order by score asc) as class_sum_score

from student s;

开窗函数 - rank

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,RANK() over (partition by class_id order by score desc) as ranking

from student s;

查询进阶 - 开窗函数 - row_number

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,ROW_NUMBER() over (partition by class_id order by score desc) as row_number

from student s;

开窗函数 - lag / lead

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,

LAG(name,1,null) over (partition by class_id order by score desc) as prev_name,

LEAD(name,1,null) over (partition by class_id order by score desc) as next_name

from student s;

相关推荐
独行soc23 分钟前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍08-基于时间延迟的SQL注入(Time-Based SQL Injection)
数据库·sql·安全·渗透测试·漏洞挖掘
White_Mountain41 分钟前
在Ubuntu中配置mysql,并允许外部访问数据库
数据库·mysql·ubuntu
Code apprenticeship42 分钟前
怎么利用Redis实现延时队列?
数据库·redis·缓存
百度智能云技术站1 小时前
广告投放系统成本降低 70%+,基于 Redis 容量型数据库 PegaDB 的方案设计和业务实践
数据库·redis·oracle
装不满的克莱因瓶1 小时前
【Redis经典面试题六】Redis的持久化机制是怎样的?
java·数据库·redis·持久化·aof·rdb
清平乐的技术专栏1 小时前
Hive SQL 查询所有函数
hive·hadoop·sql
梦想平凡2 小时前
PHP 微信棋牌开发全解析:高级教程
android·数据库·oracle
TianyaOAO3 小时前
mysql的事务控制和数据库的备份和恢复
数据库·mysql
Ewen Seong3 小时前
mysql系列5—Innodb的缓存
数据库·mysql·缓存
码农老起3 小时前
企业如何通过TDSQL实现高效数据库迁移与性能优化
数据库·性能优化