DDL数据库定义语言

创建数据库

create database db1

如果不存在就创建

create database if not exist db1

查看所有数据库

show databases

查看某个数据库的定义信息

show create database db1

修改数据库字符

alter create database db1 character set utf-8

删除数据库

drop database b1

查看表结构

desc b1

展示创建表的sql语句

show create table b1

修改表名

alter table b1 rname to b2

添加列

alter table b1 add 列名 数据类型

删除列

alter table b1 drop 列名

删除表

drop table b1

如果纯在就删除表

drop table if exist b1

DML数据操作语言

插入所有列名数据

insert into b1(列名1,列名2,···列名n)values(值1,值2,···值n)/ insert into b1 values (值1,值2,···值n)

插入部分列名数据

insert into b1(列名1,列名2)values(值1,值2)

删除表中数据

delete from b1 where 列名 = 值

删除表中所有数据

delete from b1

删除表中所有数据(高效,先删除表,在创建一个空表)

truncate table b1;

不带条件修改

update b1 set 列名 = 值

带条件修改

update b1 set 列名 = 值 where 列名 = 值

DQL数据查询语言

查询表中数据

select * from b1

查询表中部分数据

select 列名1,列名2 from b1

带条件查询数据

select * from b1 where 列名 = 值

排序查询order by

select * from b1 order by 列名(默认升序,加desc降序)

聚合函数

avg max min sum count

分组查询group by

select gender ,avg(score)from student group by gender 按照性别进行分组,查询男女同学的平均分

select gender ,avg(score),count(id)from student group by gender按照性别进行分组,查询男女同学的平均分和人数

分页查询limit 开始索引,条数

select * from b1 limit 0,3

select * from b1 limit 3,3

select * from b1 limit 6,3

子查询:查询中嵌套查询

select student_name, ( select AVG(score) from grades where grades.student_id = students.student_id ) from students 查询每个学生的平均分数。

select * from students where age = (select max(age) from students)查询年龄最高的人的信息

连接查询

select * from b1 left join b2 on 条件

select * from b1 right join b2 on 条件

举例:

select customers.customer_name, orders.order_id, orders.order_date
from customers left join orders on customers.customer_id = orders.customer_id;

查询每个用户以及他的订单