目录
DML(Data Manipulation Language)
通用语法
SQL语句可以单行/多行书写,以分号结束
SQL语句可以增加缩进/空格来增进可读性
SQL语句的关键字不区分大小写
单行注释(--注释)
多行注释(/*注释*/)
分类
DDL(Data Definition Language)
数据定义语言,用来定义数据库对象(数据库,表)
数据库
查询所有数据库:show databases;
查询当前数据库:select database();
使用数据库:use 数据库名;
创建数据库:create database [if not exists] 数据库名;
删除数据库:drop database [if exist] 数据库名;
表
数据类型
创建
create table 表名(
字段1 类型 [约束] [comment 字段1注释],
字段2 类型 [约束] [comment 字段2注释]
) [comment 表注释];
非空约束 not null
唯一约束 unique
主键约束 primary key(auto_increment自增)
默认约束 default
外键约束 foreign key
例:
create table db_user(
id int primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
name varchar(10) not null comment '姓名',
age int comment '年龄',
gender char(1) default '男' comment '性别'
) comment '用户表';
查询
查询当前数据库所有表:show tables;
查询表结构:desc 表名;
查询建表语句:show create table 表名;
修改
添加字段:alter table 表名 add 字段名 类型 [comment 注释] [约束];
修改字段类型:alter table 表名 modify 字段名 新数据类型;
修改字段名和字段类型:alter table 表名 change 旧字段名 新字段名 类型 [comment 注释] [约束];
删除字段:alter table 表名 drop column 字段名;
修改表名:rename table 表名 to 新表名;
删除
删除表:drop table [if exists] 表名;
DML(Data Manipulation Language)
数据操作语言,用来对数据库中表的数据进行增,删,改操作
添加数据
指定字段添加数据:insert into 表名(字段名1,字段名2) values (值1,值2);
全部字段添加数据:insert into 表名 values (值1,值2);
指定字段批量添加数据:insert into 表名(字段名1,字段名2) values (值1,值2),(值1,值2);
全部字段批量添加数据:insert into 表名 values (值1,值2),(值1,值2);
修改数据
update 表名 set 字段名1=值1,字段名2=值2,…… [where 条件];
删除数据
delete from 表名 [where 条件];
如果要删除某一字段的值,可以使用update,将该字段的值置为null
DQL(Data Query Language)
数据查询语言,用来查询数据库表中的数据
基本查询
查询多个字段[设置别名]:select 字段1 [as 别名1],字段2 [as 别名2] from 表名;
查询所有字段:select * from 表名;
去除重复记录:select distinct 字段列表 from 表名;
条件查询(where)
select 字段名 from 表名 where 条件列表;
分组查询(group by)
select 字段列表 from 表名 [where 条件列表] group by 分组字段名 [having 分组后过滤条件];
例:select job,count(*) from users where entrydata<='2015-1-1' group by job having count(*)>=2;
where 与 having 的区别:
1,执行时机不同: where是分组之前进行过滤 , 不满足where条件 , 不参与分组 ; having是分组之后对结果进行过滤
2,判断条件不同: where不能对聚合函数进行判断,而having可以
排序查询(order by)
select 字段列表 from 表名[where 条件列表][group by 分组字段名]order by 字段1 排序方式1,字段2 排序方式2;
分页查询(limit)
select 字段名 from 表名 limit 起始索引,查询记录数;
其中:起始索引=(查询页码-1)*每页显示记录数
DCL(Data Control Language)
数据控制语言,用来创建数据库用户、控制数据库的访问权限
多表设计
一对多
在多的一方添加外键,关联另外一方的主键
一对一
任意一方,添加外键,关联另外一方的主键
多对多
借助中间表,中间表的两个外键,分别关联另外两张表的主键
多表查询
内连接
隐式内连接:select 字段列表 from 表1,表2 where 连接条件 ……;
显示内连接:select 字段列表 from 表1 join 表2 on 连接条件……;
外连接
左外连接:select 字段列表 from 表1 left join 表2 on 连接条件 ……;
右外连接:select 字段列表 from 表1 right join 表2 on 连接条件 ……;
子查询
SQL语句中嵌套select语句,称为嵌套查询(子查询)
标量子查询
select * from t2 where 条件 =(select 字段列表 from t2 where 条件);
当(select 字段列表 from t2 where 条件)查询出来的是 单个值 时使用
列子查询
select * from t2 where 条件 in(select 字段列表 from t2 where 条件);
当(select 字段列表 from t2 where 条件)查询出来的是 一列 (多行) 时使用
行子查询
select * from t2 where (条件1,条件2)=(select 字段1,字段2 from t2 where 条件);
当(select 字段1,字段2 from t2 where 条件)查询出来的是 一行 (多列) 时使用
表子查询
当(select 字段1,字段2 from t2 where 条件)查询出来的是 多行 多列 时使用