SQL语句总结

SQL语句

limit子句用于限制查询结果返回的数量。

用法:【select * from tableName limit i,n 】

参数:

tableName : 为数据表;
i : 为查询结果的索引值(默认从0开始);
n : 为查询结果返回的数量

一个班级分数大于90分的人数占比,round函数,coucat

select round(T1.co / T2.totalCo * 100, 1)
from
(select count() AS co from student s where s.score >= 90 ) T1,
(select count(
) AS co from student ) T2;

在这里插入图片描述
分组取每组最大值

案例:按课程号分组取成绩最大值所在行的数据
我们可以使用关联子查询来实现:

select *
from score as a
where 成绩 = (
select max(成绩)
from score as b
where b.课程号 = a.课程号);

在这里插入图片描述
上面查询结果课程号“0001”有2行数据,是因为最大成绩80有2个

分组取每组最小值

案例:按课程号分组取成绩最小值所在行的数据

同样的使用关联子查询来实现

select *
from score as a
where 成绩 =
(select min(成绩)
from score as b
where a.课程号=b.课程号)

每组最大的N条记录

案例:查询各科成绩前两名的记录
课程001的

select *
from score
where 课程号= ‘001’
order by 成绩 desc
limit 2

查询各科成绩前两名的记录

(select * from score where 课程号='001' order by 成绩 desc limit 2 )
union all
(select * from score where 课程号='002' order by 成绩 desc limit 2)
union all
(select * from score where 课程号='001' order by 成绩 desc limit 2)

插入数据

select * from table limit 2,1;                
 
//含义是跳过2条取出1条数据,limit后面是从第2条开始读,读取1条信息,即读取第3条数据select * from table limit 2 offset 1;     
 <> // 不等于
//含义是从第1条(不包括)数据开始取出2条数据,limit后面跟的是2条数据,offset后面是从第1条开始读取,即读取第2,3条
create table emp1 (
     id INT NOT NULL AUTO_INCREMENT,
     name vachar(30),
     PRIMARY KEY (id)
     );

insert into score(学号,课程号,成绩)
values ('001','001',80)

select employee_id, last_name, salary, department_id
from employees
where department_id in (70, 80) --> 70:1 80:34
–union 并集
–union all(有重复部分)
–intersect 交集
–minus 相减
select employee_id, last_name, salary, department_id
from employees
where department_id in (80, 90) --> 90:4 80:34

【重要】

DDL :数据定义语言 create table …/ drop table … / rename … to…/ truncate table…/alter table …
DML : 数据操纵语言
insert into … values …
update … set … where …
delete from … where …
select … 组函数(MIN()/MAX()/SUM()/AVG()/COUNT())
from …join … on … 左外连接:left join … on … 右外连接: right join … on …
where …
group by … (oracle,SQL server中出现在select 子句后的非分组函数,必须出现在 group by子句后)
having … 用于过滤 组函数
order by … asc 升序, desc 降序
limit (0,4) 限制N条数据 如: topN数据

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值