SQL查询语句总结

基本查询

1.查询全表的数据
select * from 表名;
select 属性1,属性2,属性3,属性4 from 表名;

2.查询指定数据(where条件)
select * from 表名 where 筛选条件 ;
select 属性1,属性2,属性3,属性4 from 表名 where 筛选条件;

3.使用集合函数查询
函数(属性)属性作为函数的参数
注意:使用函数时,首先需要考虑是否需要分组
count(); 数量
sum(); 求和
avg(); 平均
max(); 最大
min(); 最小

注意:
(1)%代表数量和类型都不知的多个字符,_只能代表一个字符。
(2)LIMIT,使用LIMIT可以实现分页功能,
LIMIT
select * from student where name like ‘小%’ LIMIT 3;(显示三条信息,不一定按顺序显示前三条)
LIMIT off , len
off表示起始位置(off=0可以省略),len表示长度
select * from student where name like ‘小%’ LIMIT 0,3;
(3)排序 :order by
order by 属性;默认升序 asc
order by 属性 desc;降序
按照某个属性分组:group by 属性 分组
select * from student where group by sex;
(4)分组 :group by
使用group by后面不能跟where 需要跟having+判断条件,与where作用相同,但是两表的关联关系必须用where,可以用在group by前面
select name,avg(score) from 表名 group by courses_id having
例如:
select Student.*,cast(avg(SC.score) as dec(4,2)) 平均分 from SC,Student where SC.SID = Student.SID group by SID having cast(avg(SC.score) as dec(4,2)) > 60 order by avg(SC.score);

多表查询—联合查询

联合查询分为内连接查询与外连接查询

1.内连接查询:把意义相同的字段相等时的数据过滤出来
内连接方式一:
select a.,b.属性 from 表1 a,表2 b,表3 c… where a.EX = b.EX and b.EX = c.EX;
内连接方式二:on后面接连接条件*
select a.*,b.属性 from 表1 a join 表2 b on 表1.EX = 表2.EX join 表3 c on 表2.EX = 表3.EX …

2.外连接查询:外连接会出现null字段
左连接查询:以左边的表为主,展示左表的全部信息,属性无值时,用null表示
select a.**,b.属性 from 表1 a left join 表2 b on 表1.EX = 表2.EX left join 表3 c on 表2.EX = 表3.EX …*
右连接查询:以右边的表为主,展示右表的全部信息
select a.*,b.属性 from 表1 a right join 表2 b on 表1.EX = 表2.EX right join 表3 c on 表2.EX = 表3.EX …

多表查询—子查询

子查询由内层查询语句和外层查询语句组成。
内层查询的结果作为外层查询的条件。
如:select * from A where age > (select age from B);

1.带in关键字的子查询
in: 后面跟集合
not in
A: id 70 90 90
B: id 40 89 78 70
select * from A where id (not) in (select id from B);
select * from A wnere id (not) in (40,89,78,70);

2.带比较运算符的子查询
= !=(<>) > < >= <= 后面跟单个数据
比较运算符不能和多个进行数据集合进行比较
select * from A where age > (select id from B where 筛选条件);
(select id from B where 筛选条件); 内层查询的结果为一个数据值,不能为集合
select * from A where age > 40;

3.带exists关键字的子查询
select * from A where exists (select id from B where 筛选条件)
内层查询不返回查询结果,而是返回一个真假值true or false。如内层能查到数据就返回true。
true:外层查询会执行
false:外层不会执行
两个语句没有联系

4.带any关键字的子查询: 任何一个
满足内层查询语句返回的结果中的任何一个即可
select * from id where age > any (select id from B where 筛选条件);
select * from id where age > any (40,89,78,70); 大于任何一个

5.带all关键字的子查询:全部
满足内层查询语句返回的所有结果
select * from id where age > all (select id from B where 筛选条件);
select * from id where age > all(40,89,78,70); 大于所有

注意:
如果是数据集合可以用in、not in、all、any
如果是一个数据用 大小 等于比较

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值