SQL
DDL:定义数据库对象(数据库、表、字段)
- 查询
show databases; --查询所有数据库
show tables;
desc 表名; --查询表结构
show create table 表名 ; 插叙指定表的建表语句
select database(); --查询当前数据库
- 创建
create database [if not exists] 数据库名 [default charset utf8mb4] [collate 排序规则];
create table 表名(
字段1 字段1类型 [comment 字段1注释],
age int comment "年龄",
name varchar(20) comment "用户名",
...
)[comment 表注释];
- 删除
drop database [if exists] 数据库名;
drop table [if exists] 表名;
truncate table 表名; --删除指定表,并重新创建该表
alter table 表名 drop 字段名; --删除字段
- 使用
use 数据库名;
- 修改
alter table 表名 add 字段名 类型(长度)[comment 注释];
alter table 表名 modify 字段名 新数据类型(长度); --修改数据类型
alter table 表名 旧字段名 新字段名 类型(长度)[comment 注释] [约束]; --修改字段名和字段类型
alter table 表名 rename to 新表名; --修改表名
DML:对数据库表中的语言增、删、改
- 添加数据
insert into 表名(字段名1,字段名2,...)values(值1,值2...);
insert into 表名 values(值1,值2...); --给全部字段添加数据
insert into 表名(字段名1,字段名2,...)values(值1,值2...),(值1,值2...),(值1,值2...); --批量添加
insert into 表名 values(值1,值2...),(值1,值2...),(值1,值2...);
- 修改数据
update 表名 set 字段名1 = 值1,字段名2 = 值2 [where 条件];
- 删除数据
delete from 表名 [where 条件];
DQL:查询数据库中表的记录
DQL执行顺序:from 、where、 group by、 having select 、order by、limit
select 字段1,字段2 ... from 表名;
select 字段1 [as 别名1], ... from 表名; -- 设置别名
select distinct 字段列表 from 表名; --去重
select count/max/min/avg/sum(字段列表) from 表名;
select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件];
-- asc 升序(默认可省略) desc降序
select 字段列表 from 表名 order by 字段1 排序方式1,字段2 排序方式2... ;
select 字段列表 from 表名 limit 起始索引,查询记录数
--起始索引 = (查询页码-1)*每页记录数
案例:
--1、根据性别分组,统计男性员工和女性员工的平均年龄
select gender,avg(age) from emp group by gender;
--2、查询年龄小于45,根据工作地址分组,获取员工数量大于3的工作地址
select workaddress,count(*) from emp group by workaddress having count(*)>=3;
DCL:创建数据库用户、控制数据库访问权限
- 用户管理
- 查询用户
user mysql;
select * from user;
- 创建用户
create user '用户名'@'主机名' identified by '密码';
- 修改用户密码
alter user '用户名'@'主机名' identified with mysql_native_passord by '新密码';
- 删除用户
drop user '用户名'@'主机名';
- 权限控制
- 查询权限
show grants for '用户名'@'主机名';
- 授予权限
grant 权限列表 on 数据库名.表名 to '用户名'@'主机名';
- 撤销权限
revoke 权限列表 on 数据库名.表名 from '用户名'@'主机名';