Day019-2021-08-24 高级查询

第十九天,SQL的一些高级用法

一、高级查询

1.1 建表

drop table if exists tb;
creat table tb
(
id int primary key auto_increment,
col1 varchar(10),
col2 date,

)

1.2 分组查询

select col1,聚合函数(col2) 别名
from tb
where …
group by col1
having …;

1° 聚合函数又叫做组函数:

  1. max() 取最大
  2. min() 取最小
  3. avg() 取平均
  4. sum() 求和
  5. count() 计数

2° where 和 having

两者都用于过滤,where用于分组前,having用于分组后。

1.3 子查询

select from tb where col in ();
select from tb where exists ();
两者括号内都可以放入一个子查询。
in 操作先处理子查询,子查询返回一个结果集,然后在主查询里筛选出最终结果。
exists 操作先处理主查询,再针对每一条结果用子查询来判断,最终结果显示所有子查询返回为真的条目。
所以,主查询范围小的建议用 exists,子查询范围小的建议用 in。

1.4 联表查询

1° 联表格式

select col1,col2,col3…
from tb1
inner join tb2
on tb1.col=tb2.col;

2° 联表种类

  1. 内联 inner join 只会包含所有两表能匹配到的条目
  2. 左联 left join 会保证包含左表的全部数据
  3. 右联 right join 会保证包含右表的全部数据
  4. 全外联 full out join 结果拥有两个表的全部数据
    MySQL中没有全外联的语法

1.5 联合查询

1° 联合格式

select *
from tb1
union
select *
from tb2;
联合是将两个表合并为一个表。

2° union 与 union all

union 会去除重复部分,
union all 会保留全部数据

3° 联合查询实现全外联

将两表的左联结果与右联结果进行联合查询操作。

1.6 排序

select *
from tb
order by col asc/desc

1.7 case-when-then-end 语句

select col1,col2,col3,…,
case
when col<=val1 then ‘A’
when col>val1 and col<=val2 then ‘B’
when col>val2 and col<=val3 then ‘C’

end
from tb;
常用于对一个字段进行评级操作。

1.8 表的复制

insert into tb2
select * from tb1;

1.9 表的清空

delete from tb;
truncate tb;
delete 只是数据上的删除,不重置主键;
truncate 是整表清除,同时会重置主键。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值