以下为自己整理的一些MySQL数据库的常用操作语句:
注意: 语句结束后,用英文“;”结束
1. 显示所有数据库
show databases;
2. 建立数据库
create database 数据库名称;
3. 进入数据库/使用数据库
use 数据库名称;
4. 查看当前数据库
select datebase();
5. 创建表
create table 表名 (字段名 字符类型 属性);
注:字段的属性根据实际使用情况而定(如: unquit 唯一,not null 非空,enum(值1,值2,......值n) 枚举 等)
6. 查看所有表
show tables;
7. 查看表结构
desc 表名;
8. 插入/增加数据
insert into 表名 (字段名1,字段名2,......,字段名n) values (值1,值2,......,值n);
9. 连续插入多行输入(用“,”隔开)
insert into 表名 (字段名1,字段名2,......,字段名n) values (值1,值2,......,值n),(值1,值2,......,值n),(值1,值2,......,值n);
10. 查询指定表(查看表数据)
select * from 表名;
11. 删除表的两种方式,第1种 先判断表是否存在,如存在执行删除,如不存在提示该表不存在;第2种 不判断,直接删除该表
第1种:drop table if exists 表名;
第2种:drop table 表名;
12. 新建表,字符类型为 无符号 型
create table 表名 (字段名 字符类型 unsigned);
PS:有符号与无符号的区别,有符号区间(-128,127),无符号区间(0,255),有符号含有正负号,无符号只有正数
例:create table student (ID int(4) unsigned);
13. 新建表,字段内容自动补零(如:学号为数据库设定长度8位,实际长度为6位,剩余两位用0补齐)
create table 表名 (字段名 字符类型 zerofill);
数据展现形式: 00201708 张三 男 19920527 174 一班
14. 新建表时设置表的字符类型位UTF-8
create table 表名 (字段名 字符类型)charset utf8;
15. 显示某几行数据(limit)
select * from 表名 order by 字段名 desc limit n;
PS:n 为用户给定值,该条语句是查询 n 条数据,比如:10条数据 select * from 表名 order by 字段名 desc limit 10;
limit:实际语法为 limit x,y,默认从第 x+1 行开始,显示y行,与排序联合使用(order by)
16. 正序/倒序的语法( order by )
正序(从小到大): select * from 表名 order by 字段名;
倒序(从大到小): select * from 表名 order by 字段名 desc;
17. 分组的语法( group by )
select 字段名 from 表名 group by 字段名 having 条件; 注: having 等同于 where
例:select name from student group by name; 按name分组
18. 修改表名
alter table 旧表名 rename 新表名;
19. 增加列
alter table 表名 add 字段名 字符类型;
20. 删除列
alter table 表名 drop 字段名;
21. 修改字段名
alter table 表名 change 字段名 新字段名 字符类型;
22. 修改字段属性
alter table 表名 modify 字段名 字符类型;
23. 更新数据
update 表 set 新数据 where 条件;
24. 删除数据(表后面不加 where 条件,清空表数据)
delete from 表 where 条件;
delete from 表;