MySQL 基础教程
DDL数据库定义语言
数据库
操作语法
查询所有数据库
1
show databases;
查询当前数据库
1
select database();
使用/切换数据库
1
use 数据库名;
创建数据库
1
create database [if not exists] 数据库名 [default charset utf8mb4];
MySQL8.0 版本及以上字符集默认为 utf8mb4
删除数据库
1
drop database [if existe] 数据库名;
以上的 database 均可替换成 plaintext schema 如: sql creat schema database db01;
注:在 show 语句中把 databases 替换成 schemas 需要加 s 作为复数形式
表结构
创建
1 | creat table tablename ( |
约束:非空约束plaintext not null
唯一约束plaintext unique
主键约束plaintext primary key
默认约束plaintext default
外健约束plaintext foreign key
查询、修改、删除
查询当前数据库所有表
1
show tables
查看表结构
1
show 表名;
查询建表语句
1
show create table 表名;
添加字段
1
alter table 表名 add 字段名 类型 [约束] [注释];
修改字段类型
1
alter table 表名 modify 字段名 类型 [注释];
修改字段名
1
alter table 表名 change 字段名 新字段名 类型 [注释];
删除字段
1
alter table 表名 drop column 字段名;
修改表名
1
alter table 表名 rename to 新表名;
删除表
1
drop table 表名;
DML 数据库操作语言 增删改
insert
指定字段添加数据 *
1
insert into 表名 (字段1,字段2...) values (值1,值2);
全部字段添加数据
1
insert into 表名 values (值1,值2);
指定字段批量添加数据 *
1
insert into 表名 (字段1,字段2...) values (值1,值2), (值1,值2);
全部字段批量添加数据
1
insert into 表名 values (值1,值2), (值1,值2);
updata
修改单个数据
1
updata 表名 set 字段 = '值', 字段 = '值' [where id = '值'];
修改全部数据
1
updata 表名 set 字段 = '值', 字段 = '值';
dalete
删除单条数据
1
delete from 表名 where id = '值';
删除全部数据
1
delete from 表名;
DQl
基本查询
查询多个字段
1
select 字段1,字段2,字段3 from 表名;
查询所有字段
1
select * from 表名;
为查询字段设置别名,as 关键字可以省略
1
select 字段1 [as 别名1],字段2[as 别名2] from 表名;
去除重复记录
1
select distinct 字段列表 from 表名;
条件查询
1 | select 字段列表 from 表名 where 条件列表; |
聚合函数
count
1
select count(id) from 表名;
1
select count(*) from 表名;
1
select count(1) from 表名;
其他
1
select max(字段) from 表名;
1
select min(字段) from 表名;
1
select avg(字段) from 表名;
1
select sum(字段) from 表名;
1 | select |
分组查询
1 | select 字段列表 from 表名 [where 条件列表] group by 分组字段名 [having 分组后过滤条件]; |
1 | select job, count(*) from emp where data <= '2015-01-01' group by job havin count(*) >= 2; |
where 和 havin 的区别:
- 执行时机不同 (where -> group by -> having)
- 判断条件不同 (having 后可以用聚合函数,where 不可以)
排序查询
1 | select 字段列表 from 表名 [where 条件列表] [group by 分组字段名 having 分组后过滤条件] order by 排序字段 排序方式 |
1 | select * from emp order by entry_date asc, update_time desc; |
升序:asc (默认) 降序:desc
分页查询
1 | selece 字段列表 from 表名 [where 条件] [group by 分组字段 having 过滤条件] [order by 排序字段] limit 起始索引, 查询记录数; |
起始索引为 0 时可以省略
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Lathezero's Blog!
评论