# 查看所有的数据库
show databases;
# 使用数据库
use 数据库名;
# 查看当前使用的数据库
select database();
# 创建数据库
create database 数据库命 charset=utf8;
# 删除数据库(谨慎使用!!!)
drop database 数据名;
数据表基本操作
# 查看当前数据库中的所有表
show tables;
# 查看表结构
desc 表名;
# 创建表
create table 表名(字段名 类型 约束);
# 修改表-添加字段
alter table 表名 add 字段名 类型;
# 修改表-修改字段-重命名
alter table 表名 change 原表名 新表名 类型以及约束;
# 修改表-修改字段-不重命名
alter table 表名 modify 字段名 类型以及约束;
# 修改表-删除字段
alter table 表名 drop 字段名;
# 删除表(谨慎使用!!!)
drop table 表名;
# 查看表的创建语句
show create table 表名;
数据的基本操作
# 基本查询-查询所有
select * from 表名;
# 指定列查询
select 字段1名, 字段2名 from 表名;
# 添加数据
insert into 表名 values(添加的数据);
# 修改数据
update 表名 set 字段=值 where 条件;
# 删除(谨慎使用!!!)
delete from 表名 where 条件;
数据查询进阶
# 别名查询
select 字段名 as 别名 from 表名;
# 消除重复行
select distinct 字段名 from 表名;
# 比较运算符查询
select * from 表名 where 查询条件 例如: height > 175;
# 逻辑运算符查询
select * from 表名 where id>3 and gender=1;
select * from 表名 where id>3 or gender=1;
# 模糊查询
# 例如 查询姓曾的
select * from 表名 where name like "曾%";
# 非连续范围查询
# 例如:查询年龄位18到30岁的
select * from 表名 where age in (18, 30);
# 连续范围查询
# 例如:查询年龄到30之间的
select * from 表名 where age between 18 and 34;
# 排序
select * from 表名 order by 字段名 desc(降序) 或者 asc(升序)
# 聚合函数
# 求总数 select count(*) from 表名
# 求和 select sum(字段名) from 表名;
# 最大值 ...同上...max(字段名) ...同上...
# 最小值 ... ...min(字段名) ... ...
# 平均值 ... ...avg(字段名) ... ...
# 分组查询
select * from 表名 group by 字段名;
# 分页查询
select * from 表名 limit 当前第几页,每页显示多少数据;
# 连接查询
# 内连接
select * from 表名1 inner join 表名2 on 表名1.字段名 = 表名2.字段名
# 左连接
select * from 表名1 left join 表名2 on 表名1.字段名 = 表名2.字段名
# 右连接
select * from 表名1 right join 表名2 on 表名1.字段名 = 表名2.字段名