Mysql

关注公众号 jb51net

关闭
首页 > 数据库 > Mysql > mysql DML的select分组排序

mysql之DML的select分组排序方式

作者:Computer Virus

在此教程中,我们详细介绍如何创建员工(employee)和部门(department)数据库表,并展示了如何通过SQL语句进行数据插入、删除和查询,首先,创建了部门表并自动设置部门编号起始值为1001,接着创建员工表并定义了各字段,我们还设置了外键关联两表

一、创建表employee和department表

1.创建department表

create table department(
-> depart_id int primary key auto_increment comment '部门编号',
-> depart_name varchar(50) not null comment '部门名称'
-> ) auto_increment=1001;

2.创建employee表

create table employee( n for the right syntax to use near 'redsodsnvjnv' at line 1
-> emp_num int primary key auto_increment comment '员工编号',
-> emp_name varchar(30) not null comment '员工姓名',
-> emp_job varchar(30) not null comment '员工岗位',
-> hire_data datetime not null comment '入职时间',
-> salary int not null comment '薪资',
-> bonus int not null comment '奖金',
-> dept_id int comment '部门编号'
-> );

3.给employee表格和department表格建立外键

alter table employee add constraint emp_dept_fk foreign key(dept_id) references department(depart_id);

4.给department插入数据

insert into department values(null,'科技部门'),(null,'法律部门'),(null,'后勤部门'),(null,'财务部门');

5.给employee表插入数据

insert into employee values((null,'张三','工程师','2023.9.1',12000,1000,1001),(null,'张四','工程师','2023.9.1',11000,1010,1001),(null,'李三','会计','2023.9.1',5000,300,1004),(null,'张六','保安','2023.9.1',5000,500,1003),(null,'刘律','律师','2023.9.1',1000,1,1002);

6.删除名字为那个的数据

delete from employee where emp_name='那个';

二、分组查询和排序查询,以及对数据的处理(avg,sum,count,max,min)

1.根据dept_id进行分组并查询他们的平均工资

select dept_id,avg(salary) from employee group by dept_id;

2.根据dept_id分组查询他们年薪平均值

select dept_id, avg((salary+bonus)*12) from employee group by dept_id;

3.根据dept_id分组查询他们薪资的最高值

select dept_id,max(salary) from employee group by dept_id;

4.根据dept_id分组查询他们薪资的最低值

select dept_id,min(salary) from employee group by dept_id;

5.根据dept_id分组查询他们薪资的总和

select dept_id,sum(salary) from employee group by dept_id;

6.根据dept_id分组查询人数的总和

select dept_id,count(*) from employee group by dept_id;

7.根据dept_id分组查询人数的总和

select dept_ip,count(emp_name) from employee group by dept_id;

8.按照dept_id降序的方式查询emp_name和dept_id

select emp_name,dept_id from employee order by dept_id;

9.按照dept_id和emp_job分组查询薪资总和

select dept_id,emp_job,sum(salary) from employee group by dept_id, emp_job;

10.在dept_id组中限制只查询工资总和大于10000的薪资,并展现出来工作和薪资

select dept_id,emp_job,sum(salary) from employee group by dept_id,emp_job having sum(salary>1000);

三、select查询之limit限制

1.查询前三行数据

select * from employee limit 0,3;

2.查询第三条到第七条数据

select * from employee limit 2,7;

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文