mysql学习笔记

1、建库

create database 库名;
create database 库名 character set=utf8;

2、建表
create table 表名
(
字段名 数据类型 约束,
字段名 数据类型 约束,
字段名 数据类型 约束
);
3、数据类型
int float char varchar text timestamp enum
4、约束
primary key
foreign key
not null
null
unique
default
auto_increment

5、修改表结构
1)修改表名
alter table 表名 rename to 新表名;
2)添加字段
alter table 表名 add column 字段名 数据类型 约束;
alter table 表名 add 字段名 数据类型 约束;
3)删除字段
alter table 表名 drop column 字段名;
alter table 表名 drop 字段名;
4)修改字段
alter table 表名 change 原字段名 新字段名 数据类型 约束;

6、删除表
drop table 表名;
7、添加记录
insert into 表名(字段...)values(值...);
8、修改记录
update 表名 set 字段=值,字段=值...;
update 表名 set 字段=值,字段=值... where 条件;
9、删除记录
delete from 表名;
delete from 表名 where 条件;
10、清空表
delete from 表名; 不恢复id 慢 可恢复 支持事务
truncate table 表名; 恢复id 快 不恢复 不支持事务

11、普通查询
select * from 表名;
select 字段,字段... from 表名;
12、条件查询
select * from 表名 where 条件;
13、排序
select * from 表名 order by 字段;#升序
select * from 表名 order by 字段 desc;#降序
select * from 表名 where 条件 order by 字段;
14、分组
select * from 表名 group by 字段;
15、聚合查询
select count(*) from 表名 where 条件;
select sum(字段) from 表名 where 条件;
select avg(字段) from 表名 where 条件;
select max(字段) from 表名 where 条件;
select min(字段) from 表名 where 条件;
16、分页查询
select * from 表名 limit 起始值,条数;
select * from 表名 where 条件 order by 字段 limit 起始值,条数;
17、模糊查询
select * from 表名 where 字段 like '%_内容';
通配符
%:任意长度的任意字符
_:任意一个字符

18、多表查询

1)查询所有姓张的学生
select * from 学生表 where 姓名 like '张%';
2)查询所有姓张的学生,但名字必须是两个字
select * from 学生表 where 姓名 like '张_';
3)查询所有学生,但姓名中必须有"小"字
select * from 学生表 where 姓名 like '%小%';

19、子查询(嵌套查询)
1)子查询出现where中,充当条件
select * from 表名 where 字段 in (select语句);
2)子查询出现在*中,充当字段
select 字段,字段,(select语句) from 表名;

原文地址:https://www.cnblogs.com/siyz/p/11426693.html