一、创建表
create table 表名(字段名 字段类型 字段约束,....)
例如:
create table student(
id int unsigned not null auto_increment primary key,
name char(20),
age int,
gender char(1),
email varchar(32),
class varchar(32)
)charset=utf8;
1.查看建表语句
show create table 表名;
2.查看表结构
desc 表名;
3.删除表
drop table 表名;
二、数据的基本操作
1.添加数据
指定所有字段添加数据:
insert into 表名(字段名,字段名......)
values(值,值......)
不指定所有字段添加数据:
insert into 表名 values(值,值......),值的顺序不必须按照表结构来添加
指定部分字段添加:
insert into student (字段1,字段5.....)
values(值1,值5.....)
2.查询数据
select * from 表名,*代表所有字段
3.修改数据
update 表名 set 字段名=值 where 条件
4.删除数据
delete from 表名 where 条件
三、MySQL数据类型
1.数值类型
常用:
int 4个字节
Tinyint 1个字节
Decimal 格式decimal(245,1)23.5
2.字符串类型
char 定场字符串
varchar 变长字符串
3.事件日期类型
datetime混合事件日期类型 格式yyyy-mm-dd hh:mm:ss
4.常见的字段约束
Unsigned 无符号
Int 显示宽度
Not null 非Null
Default 默认
Primary key 主键,不可为空
Unique 唯一约束,可以为空
Auto_increment 自动递增
四、表结构的操作
添加字段add
alter table 表名 add 字段名 字段约束
修改字段modify/change
alter table 表名 modify/change 字段名
注意只有change可以修改字段的名称
删除字段
alter table 表名 drop 字段名
修改表名
alter table 表名 rename as 表名
五、运算符
算术运算符: + - * / %
比较运算符:> < >= <= = != <>
特殊比较运算符:in, not in,is null,is not null,like,between and
逻辑运算符:and or not
逻辑运算符优先级 or<and<not
六、模糊查询
like 有两个
% 任意位的任意字符
_ 一位任意字符
例如:
SELECT * FROM students WHERE name like '小%'
七、聚合函数
Max() min() count() avg() sum()
例如:
SELECT max(age),min(age),avg(age) FROM students WHERE class='python';
八、去重
distinct
例如:
select distinct class fromstudent;
九、分组group by和having字句
分组查询
例如:
SELECT class FROM students GROUP BY class;
条件分组查询
例如:
SELECT class,count(*) FROM students GROUP BY class HAVING count(*)>2;
注意:having子句只能在分组后面使用!