课程回顾:
- 数据库相关SQL
- 查询所有 show databases;
- 创建 create database db1 charset=utf8/gbk;
- 查看数据库信息: show create database db1;
- 删除数据库: drop database db1;
- 使用: use db1;
- 表相关SQL
- 创建表: create table t1(name varchar(20),age int) charset=utf8/gbk;
- 查询所有: show tables;
- 查询表信息: show create table t1;
- 表字段: desc t1;
- 删除表: drop table t1;
- 修改表名: rename table t1 to t2;
- 添加表字段: alter table t1 add gender varchar(5) first/after xxx;
- 删除表字段: alter table t1 drop gender;
- 修改表字段: alter table t1 change 原名 新名 新类型;
- 数据相关SQL
- 插入: insert into t1(字段1名,字段2名) values(值1,值2),(值1,值2),(值1,值2);
- 查询: select name,age from t1 where 条件;
- 修改: update t1 set xxx=xxx,xxx=xxx where 条件;
- 删除: delete from t1 where 条件;
综合练习题2
- 创建数据库newdb1, 字符集utf8并使用
create database newdb1 charset=utf8;
use newdb1; - 在数据库中创建员工表emp 字段:id,name,sal(工资),deptId(部门id) 字符集utf8
create table emp(id int,name varchar(50),sal int,deptId int)charset=utf8; - 创建部门表dept 字段:id,name,loc(部门地址) 字符集utf8
create table dept(id int,name varchar(20),loc varchar(50))charset=utf8; - 部门表插入以下数据: 1 神仙部 天庭 2 妖怪部 盘丝洞
insert into dept values(1,‘神仙部’,‘天庭’),(2,‘妖怪部’,‘盘丝洞’); - 员工表插入一下数据: 1 悟空 5000 1 , 2 八戒 2000 1 , 3 蜘蛛精 8000 2 , 4 白骨精 9000 2
insert into emp values(1,‘悟空’,5000,1),(2,‘八戒’,2000,1),(3,‘蜘蛛精’,8000,2),(4,‘白骨精’,9000,2); - 查询工资6000以下的员工姓名和工资
select name,sal from emp where sal<6000; - 修改神仙部的名字为取经部
update dept set name=‘取经部’ where name=‘神仙部’; - 给员工添加奖金comm字段
alter table emp add comm int; - 修改员工表中部门id为1的 奖金为500
update emp set comm=500 where deptId=1; - 把取经部的地址改成五台山
update dept set loc=“五台山” where name=‘取经部’; - 修改奖金字段为性别gender字段 类型为varchar
alter table emp change comm gender varchar(5); - 修改孙悟空和猪八戒性别为男
update emp set gender=‘男’ where deptId=1; - 删除没有性别的员工(null不能用= 要用is)
delete from emp where gender is null; - 删除性别字段
alter table emp drop gender; - 删除表 和 删除数据库
drop table emp;
drop table dept;
drop database newdb1;
SQL分类
- DDL: 数据定义语言, 包括: 数据库向和表相关的SQL
- DML: 数据操作语言, 包括: 增删改查
- DQL: 数据查询语言, 只包括查询 select
- TCL: 事务控制语言, 包含和事务相关的内容
- DCL: 数据控制语言, 包含用户管理,权限分配相关SQL
*.sql 批处理文件
- 把老师的emp.zip解压出来得到一个emp.sql文件, 把这个文件放到某个盘的根目录 比如 D盘根目录, 然后在命令行执行以下指令
- 格式: source 路径; 举例: source d:/emp.sql;
- 测试:
show databa