数据库操作
- 创建数据库:
create database 数据库名 charset=utf-8; - 展示所有数据库:
show databases; - 切换数据库:
use 数据库名; - 查看当前选择的数据库:
select database(); - 删除数据库:
drop database 数据库名;
表操作
创建表:
create table 表名(id int auto_increment primary key not null, 字段1 varchar(5) not null , 字段2 decimal(4,1),字段3 bit default 1 );decimal(4,1)表示浮点数,一共4位,小数点占一位,整数3位。展示表:
show tables;删除表:
drop table 表名;查看表结构:
desc 表名;更改表名称:
rename table 源表名 to 新表名;查询数据:
select * from 表名 where 条件;删除数据:
delete from 表名 where 条件;逻辑删除:可修改 isDelete字段值插入一条数据:
insert into 表名(字段1, 字段2) values(值1, 值2);插入多条数据:
insert into 表名(字段1, 字段2) values(值1, 值2), (值1, 值2);修改数据:
update 表名 set 字段=值,... where 条件;-
数据备份:
- 进入超级管理员
sudo -s - 进入mysql酷目录
cd /var/lib/mysql mysqldump -uroot -p 数据库名 > 要备份的文件路径
- 进入超级管理员
-
数据恢复:
- 创建新的数据库
mysql -uroot -p 新的数据库名 < 备份的文件路径
查询-比较运算符:
select * from 表名 where 字段(=,!=,>=,<=,>,<)值;逻辑运算符:
select * from 表名 where 字段1=值1 (and,or)字段2=值2;模糊查询:
select * from 表名 where 字段 like '%gao';% 表示任意多个字符, _表示一个任意字符范围查询:
select * from 表名 where 字段 in ('值1','值2');表示字段在值1或者值2中查找,不连续。select * from 表名 where 字段 between 值1 and 值2;表示在值1到值2之间查找,连续的。空判断:
select * from 表名 where 字段 is null;。select * from 表名 where 字段 is not null;聚合函数:
select count(*) from 表名;总行数。select max(id) from 表名;根据id字段最大值。select min(id) from 表名;根据id字段最小值。select avg(id) from 表名;根据id字段平均值。select sum(id) from 表名;根据id字段总和。根据字段1分组并且筛选出字段1等于值1的行数数据:
select 字段1 as 字段1别名,count(*) from 表名 group by 字段1 having 字段1=值1;排序:
select * from 表名 where 字段1=值1 order by 字段2 asc;(默认升序,降序desc)分页:
select * from 表名 limit (n-1)*m,m;。 n从第一页开始,每页数据数量m,每页数据下标是从0开始。往表中添加字段:
alter table 表名 add 字段 类型;查询筛选出唯一不同的字段值:
select distinct 字段1,字段2 from 表名;连接查询:
select students.name,subjects.title,scores.score from scores inner join students on scores.stuid=students.id inner join subjects on scores.subid=subjects.id;添加外键:
stuid int,foreign key (stuid) references students(id);修改表字段属性:
alter table 表名 modify 字段 varchar(200) ;修改字段名称:
alter table 表名 change 字段 字段1 新类型;创建视图:
create view v_student as select * from students;注意相同名字的字段,要起别名创建索引:
create index 索引名字 on 表名(字段(10));int 类型可不写添加外检:
alter table 表1名 add constraint 外键名 foreign key(字段) references 表2(字段);