个人笔记-MySQL
学生表:student
字段名 | 字段类型 | 备注 |
id | int | 学生id |
name | varchar(8) | 学生姓名 |
sex | varchar(2) | 学生性别 |
class | int | 学生班级 |
score | int | 学生分数 |
教师表:teacher
字段名 | 字段类型 | 备注 |
id | int | 教师id |
name | varchar(8) | 教师姓名 |
class | int | 教师班级 |
班级表:class
字段名 | 字段类型 | 备注 |
id | int | 班级id |
name | int | 班级名字 |
teacher | int | 班级教师 |
MySQL命令:
数据库操作:
#创建数据库
create dataebase 数据库名字;
#删除数据库
drop database 数据库名字;
#展示数据库
show databases;
#选择数据库
use 数据库
数据表操作:
- 数据库中所有表
show tables;
- 建表
create table 表名 (字段 字段类型)
例子:
create table studend(
id int auto_increment,
name varchar(8) not null,
sex varchar(2) not null,
class int not null,
score int
primary key(id)
);
解释:
auto_increment:该字段自增1,多用于主键
not null:该字段非空
primary key():设置主键
- 新增数据
insert into 表名 (字段1,字段2, ···) value (值1,值2,···)
例子:
insert into student (
name,sex,class,score)
value (
'张三','男',1,89);
解释:
student的id为主键,并设置了自增1属性,系统会自动添加
单引号和双引号基本没多大区别,都可以表示字符串
可以使用*表示所有字段,但是所输入的值要与原表字段顺序一一对应
- 删除数据
delete from 表名 where 条件
例子:
delete from student where id=1;
解释:
根据where条件删除该行数据
- 更改数据
uptade 表名 set 字段1 = 新值1,字段2 = 新值2 where 条件
例子:
update student set score = 99 where id = 1
解释:
根据where条件更改字段的值
- 追加数据
update 表名 set 字段 = concat(追加值 + 字段) where 条件
update 表名 set 字段 = concat(字段 + 追加值) where 条件
例子:
#在原有数据后面添加
update student set name= concat(name + ',插班生') where id = 1
#在原有数据前面加
update student set name= concat('插班生:' + name ) where id = 1
解释:
concat函数里面,字段表示原有内容,可以在原有内容前后追加内容
- 修改替换部分数据
update 表名 set 字段 = replace(字段,被替换值,替换值) where 条件
例子
update student set name = replace(name,'张','李') where id =1
解释:
replace函数将字段中的”张“改为”李“,其他字符串内容不变
- 查询数据
select 字段1,字段2 ··· from 表名 where 条件
例子:
- 简单查询
select * from student
解释:
查询整张表所有内容
- 连表查询
select student.name, student.sex, teacher.name,class.name
from student
where student.score > 60
left join class on student.class = class.id
left join teacher on class.id = teacher.class
解释:
要求得到60分以上的学生姓名,性别,班级名字和班主任名字
left join:左连接,返回on条件中等号左边表格的所有数据和等号右边对应字段约束的数据
right join:右连接,与左连接相反
- 修改字段
- 删除字段
alter table 表名 drop 字段;
- 添加字段
alter table 表名 add 新字段 字段类型;
例子:
alter table student add age int not null after sex;
解释:
not null:设置该字段非空
after sex:设置该字段在sex字段后面,如果不设置,则系统默认将新增字段放到最后面
- 修改字段类型
alter table student modify 字段 新类型;
- 修改字段名字
alter table student change 旧字段 新字段 新字段类型;
- 修改not null的默认值
alter table student modify 字段名 字段类型 not null default 默认值;
- 修改字段默认值
alter table student alter 字段 set default 默认值;
- 删除默认值
alter table student alter 字段 drop default;