目录
DDL的基本语法
一、DDL操作库
1、创建库
create database 库名;
-- 判断是否存在然后创建:
create database if not exists 库名;
2、查看库
-- 查看所有的数据库
show databases;
-- 查看库的定义信息
show create database 库名;
3、删除库
drop database 库名;
4、使用\切换库
use 库名;
二、DDL操作表
1、创建表
create table 表名(
字段名 数据类型 属性,
字段名 数据类型 属性,
......
);
2、查看表
-- 查看表结构
desc 表名;
-- 查看建表语句
show create table 表名;
3、删除表
drop table 表名;
4、修改表\添加字段
-- 修改字段属性
alter table 表名 modify 字段 数据类型;
-- 修改字段名和数据类型
alter table 表名 change 旧字段名称 新字段名称 数据类型;
-- 添加字段
alter table 表名 add 字段 数据类型;
-- 删除字段
alter table 表名 drop 字段名;
DML基本语法
1、添加数据
insert into 表名(字段1,字段2,字段3...)values(值1,值2,值3...);
-- 全字段添加
insert into(值1,值2,值3....);
-- 从一个表复制数据到另一个已存在的表中
insert into 表1(字段,字段...) select 字段,字段... from 表2;
2、修改数据
update 表名 set 字段名=值.... where 条件;
3、删除数据
delete from 表名 where 条件;
4、清空表
truncate table 表名;
5、delete、truncate和drop的区别
- delete:只删除数据不删除索引
- truncate:清空表,删除数据和索引
- drop:删除整个表或库,删除表结构和后缀为.ibd的文件
DQL数据查询
1、简单查询
-- 全字段查询
select * from 表名;
-- 列出要查询的字段
select 字段1,字段2,字段3,..字段n from 表名;
-- 别名查询
select 字段 as 别名 from 表名;
-- 去除重复字段
select distinct 字段1,字段2.. from 表名;
2、带条件的查询
-- 带条件查询
select * from 表名 where 条件;
--模糊查询
--条件前模糊 "%条件"
--条件后模糊 "条件%"
--条件前后模糊 "%条件%"
select * from 表名 where 字段名 like "%条件"
--null查询
select * from 表名 where 字段名 is null/is not null;
-- 分组查询
select * from 表名 where 字段名 group by 字段名 having 条件;
--排序
-- desc 降序
-- asc 降序 默认为降序排序
select * from 表名 oreder by 字段名 desc/asc;
3、表联查
-- 等值联查
select * from 表1,表2 where 表1.字段名=表2.字段名;
--内联查询
select * from 表1 inner join 表2 on 表1.字段名=表2.字段名 ;
-- 外联查询
-- left join 主表在左边
-- right join 主表在右边
select * from 表1 left/right join 表2 on 表1.字段名=表2.字段名 ;
-- 链接查询
--union 去重
-- union all 不去重
select * from A
union/union all
select * from B
-- where 子查询
select * from A where a = (select a from B) ;
-- from 子查询
select * from A left join (select * from B) b1 on A.1=b1.1