作业:
1、写SQL语句,创建数据库和员工表(employee):
id name age salary dept
1 张三 20 3000 市场部
2 李四 24 4000 市场部
3 王五 27 2000 技术部
4 赵六 28 5000 技术部
5 周琪 18 6000 维修部
mysql -u root -p
root
create database home default character set utf8;
CREATE TABLE `petsystem`.`Untitled` (
`id` int(20) NOT NULL,
`name` varchar(255) NOT NULL,
`age` int(0) NOT NULL,
`salary` int(20) NOT NULL,
`dept` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
);
2、在表中插入上面的数据
insert into employee values
(1, '张三',20,3000,'市场部'),
(2, '李四',24,4000,'市场部'),
(3, '王五',27,2000,'技术部'),
(4, '赵六',28,5000,'技术部'),
(5, '周琪',18,6000,'维修部');
select * from employee;
3、更新id为2的工资,将工资加200
update employee set salary = salary + 200 where id = 2;
4、删除年龄低于20的员工
delete from employee where age < 20;
5、查询年龄超过24,工资小于5000的员工
select * from employee where age > 24 and salary < 5000;
6、工资最高的两个员工
select * from employee order by salary desc limit 2;
7、年龄最低 的一个员工
select * from employee order by age asc limit 1;
8、所有姓周的员工
select * from employee where name like '周%';
9、查询不同部门的人数
select dept,count(1) from employee group by dept;
10、查询平均工资低于4000的部门
select dept from employee group by dept having avg(salary) < 4000;
11、在插入15行数据,每5行一页,分页查询前4页数据
insert into employee values
(6, '老大',20,3200,'市场部'),
(7, '老二',24,4000,'维修部'),
(8, '老三',27,2200,'技术部'),
(9, '老四',28,5000,'技术部'),
(10, '老五',20,3200,'市场部'),
(11, '老六',24,4000,'技术部'),
(12, '老七',27,2000,'技术部'),
(13, '老八',28,5000,'维修部'),
(14, '小二',20,3200,'市场部'),
(15, '小三',24,4000,'市场部'),
(16, '小四',27,2200,'技术部'),
(17, '小五',28,5000,'维修部'),
(18, '小六',20,3300,'技术部'),
(19, '小七',24,4300,'市场部'),
(20, '小九',27,2500,'维修部'),
(21, '老幺',28,5000,'技术部'),
(22, '周琪',18,6100,'维修部');
select * from employee;
select * from employee limit 5;
select * from employee limit 5,5;
select * from employee limit 10,5;
select * from employee limit 15,5;
12、将员工表分为员工表和部门表
部门表
| id | name |
| ---- | ---- |
| 1 | 市场部 |
| 2 | 技术部 |
| 3 | 维修部 |
员工表(建立外键,引用部门表的id)
| id | name | age | salary | dept_id |
| ---- | ---- | ---- | ------ | ------ |
| 1 | 张三 | 20 | 3000 | 1 |
| 2 | 李四 | 24 | 4000 | 1 |
| 3 | 王五 | 27 | 2000 | 2 |
| 4 | 赵六 | 28 | 5000 | 2 |
| 5 | 周琪 | 18 | 6000 | 3 |
CREATE TABLE `petsystem`.`Untitled` (
`id` int(20) NOT NULL,
`name` varchar(255) NOT NULL,
`age` int(0) NOT NULL,
`salary` int(20) NOT NULL,
`dept_id` int(20) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `depy_id` FOREIGN KEY (`dept_id`) REFERENCES `petsystem`.()
);
CREATE TABLE `petsystem`.`Untitled` (
`id` int(20) NOT NULL,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
);
13、进行查询年龄超过18岁员工信息和部门名称(连接查询)
SELECT * FROM employee WHERE age = (SELECT age>18 FROM employee);
左外连接
将两张表中有关联的数据进行关联显示,但是会将左边的表的数据全部显示,哪怕没有关联。
SELECT * FROM employee e LEFT OUTER JOIN department d ON e.dept_id = d.id
注意:OUTER关键字可以不写
右外连接
将两张表中有关联的数据进行关联显示,但是会将右边的表的数据全部显示,哪怕没有关联。
SELECT * FROM employee e RIGHT OUTER JOIN department d ON e.dept_id = d.id
注意:OUTER关键字可以不写