1. 创建数据库
create database if not exists test character set uft8md4 collate utf8md4_general_ci;
use test;
set foreing_key_checks=0;
-
collate: 指定字符集的校对标准,用于做字符串的比较
-
uft8md4要求: 5.5.3+以后版本
2. 创建表
- 反引号标注的名字,被认为是非关键字
create table 'empolyee'(
'emp_no' int(11) not null,
'birth_date' date not null,
'first_name' varchar(14) not null,
'last_name' varchar(16) not null,
'gender' enum('M','F' not null),
'hire_date' date not null,
primary key ('emp_no')
) engine = innodb default charset = utf8;
3. 查看列信息
desc employee;
desc employees `%name`;
4. 增删改
4.1 insert
insert into ’表名‘(列1,列 2) values(值1,值2),
-- 自增字段、缺省字段、可为空字段可以不写
-- 主键可以不写
insert into tablename select……
-- 将 select 查询的结果插入到列表中
insert into 表明(列 1,列 2) values(值 1,值 2) on duplicate key update 列1 = 值 1
-- 如果主键冲突,唯一键冲突就执行 update 后的设置,,即不在增加主键,主键在就更新部分字段
insert ignore into 表名(列 1,列 2) values(值 1,值 2)
-- 如果主键冲突,唯一键冲突就胡烈错误返回一个警告
4.2 update 语句
update [ignore] 表名 set 列 1=值 1[,列 2 = 值 2……] [where 条件]
4.3 delete语句
delet [ignore] from 表名 [where 条件]
5. 查
select
select [distinct] 字段 [from 表名] [where 条件] [group by 条件 [asc|desc],... [with rollup]]
[ having 条件] [order by {} [asc|dest],] [limit {}] [for update|lock in share mode]
select sum(salary), count(*) from salaries;
select * from salaries group by emp_no;
select emp_no,sum(salary),min(salary),avg(salary),count(*) from salaries group by emp_no, from date;
select emp_no,sum(salary),min(salary),avg(salary),count(*) from salaries group by emp_no having avg(salary)>5000;
for update :排它锁
distinct :去重
concat:将多列信息进行相拼接
as:重新命令,可以没有,但有时会造成歧义
limit 5 offset 2 :从 3 开始向后 5 个元素
limit 2,5: 从 3开始向后5 个元素
where 子句 条件
- = 等于
- <> 不等于
>,<,>=,<= :大于,小于,大于等于,小于等于- between:在某个围之内,闭区间
- like :字符串匹配,
%表示多个字符,_表示一个字符 - in:指定针对某个列的多个可能值,需要加小括号(元组)
- and:与
- or :或(考虑优先级)
聚合索引
- count
- count(distinct)
- avg()
- min()
- sum()