SQL语句分类:
一、DDL(数据定义语言)
解释:定义和管理数据对象,如数据库,数据表等。
命令:create、drop、alter
基本语法:
库的操作:
显示所有库:show database;
创建一个库:create database 库名;
删除一个库:drop database 库名;
使用库:use 库名;
表的操作:
查看库中所有的表:show tables;
建表: create table 表名(
字段名 类型 属性 索引 注释,
字段名 类型 属性 索引 注释,
...
字段名 类型 属性 索引 注释
);
查看表结构:desc 表名;
show create table 表名;
存储引擎:ENGING=InnoDB
修改和删除数据库表:
修改表名:alter table 旧表名 rename as 新表名
修改字段:alter table 表名 modify 字段名 类型 属性
alter table 表名 change 旧字段名 新字段名 类型 属性
添加字段:alter table 表名 add 字段名 类型 属性
删除字段(危险操作):alter table 表名 drop 字段名
删除表(危险操作):alter table 表名
约束的添加:
添加非空约束:alter table 表名 modify test_student char(10) not null; 删除非空约束
添加唯一约束:alter table 表名 add unique(表字段名,字段,字段,字段);
添加主键约束:alter table 表名 add primary key(表的字段名,字段,字段);
添加外键约束:alter table 表名 add constraint N1 foreign key (表字段名) references 父表(父表字段名);
约束的删除:
删除not null约束:alter table 表名 modify 列名 类型;
删除unique约束:alter table 表名 drop index 唯一约束名;
删除primary key约束:alter table 表名 drop primary key;
删除foreign key约束:alter table 表名 drop foreign key 外键名;
二、DML(数据操作语言)
解释:用于操作数据库对象中所包含的数据
命令:insert、update、delete
基本语法:
数据增加:insert into 表名(字段名,字段名...字段名) values(值,值...值);
数据删除:关键字 delete,主要功能是删除数据库表中已有的记录,可以依照条件做修改。
delete from 表名 where 子句
where : 条件判断语句
数据修改:关键字是update,主要功能是修改数据库表中已有的记录,可以根据条件做修改
update 表名 set 字段名=值,字段名=值... where 子句
清空表:truncate 表名
三、DQL(数据查询语言)
解释:用于查询数据库数据
命令:select
基本语法:
查询:select * from 表名;
字段起别名:select 字段名 as '字段别名',字段名 as '字段别名' from 表名;
去重:select distinct 字段名1,字段名2,字段名3... from 表名;
带条件查询(where 子句):select * from 表名 where 条件;
模糊查询(like):select* from 表名 where 字段 like 条件;
在特定范围内查找:select * from 表名 where 字段 in(值1,值2...);
null值查询:select * from 表名 where 字段 is null;
聚合函数:count(字段) -- 统计个数
avg(字段) -- 平均值
sum(字段) -- 总和
max(字段) -- 最大值
min(字段) -- 最小值
分组:group by 字段
排序(order by ):select * from 表名 order by 字段名【desc/asc】
分页(limit):select * from 表名 limit
以上就是MySql最基本的语法,牢记且灵活运用。