MySQL基础语法总结(一)

156 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

数据库操作

数据库操作 关键字:create 创建数据库(增) create database 数据库名 [数据库选项]; 例如:

create database test default charset utf8 collate utf8_bin;

/数据库选项:字符集和校对规则/ 字符集:一般默认utf8; 校对规则常见: (1)ci结尾的:不分区大小写 (2)结尾的:区分大小写 (3)bin结尾的:二进制编码进行比较

/关键字:show 查看当前有哪些数据库(查)/ show databases;

/查看数据库的创建语句/ show create database 数据库名;

/关键字:alter 修改数据库的选项信息(改)/ alter database 数据库名 [新的数据库选项]; 例如:

alter database test default charset gbk;

/关键字:drop 删除数据库(删)/ drop database 数据库名;

/关键字:use 进入指定的数据库/ use 数据库名;


表的操作

表的操作 /关键字:create 创建数据表(增)/ create table 表名( 字段1 字段1类型 [字段选项], 字段2 字段2类型 [字段选项], 字段n 字段n类型 [字段选项] )表选项信息;

代码示例

create table test(
  id int(10) unsigned not null auto_increment comment 'id',
  content varchar(100) not null default '' comment '内容',
  time int(10) not null default 0 comment '时间',
  primary key (id)
)engine=InnoDB default charset=utf8 comment='测试表'

语法解析(下文MySQL列属性单独解析): 1)如果不想字段为NULL可以设置字段的属性为NOT NUL,在操作数据库时如果输入该字段的数据为NULL,就会报错. 2)AUTO_INCREMENT定义列为自增的属性,一般用于主键,数值会自动加1. 3)PRIMARY KEY关键字用于定义列为主键.可以使用多列来定义主键,列间以逗号分隔. 4)ENGINE 设置存储引擎,CHARSET 设置编码, comment 备注信息.

关键字:show 查询当前数据库下有哪些数据表(查)/ show tables;

/关键字:like 模糊查询/ 通配符:_可以代表任意的单个字符,%可以代表任意的字符 show tables like '模糊查询表名%';

/查看表的创建语句/ show create table 表名;

/查看表的结构/ desc 表名;

/关键字:drop 删除数据表(删)/ drop table [if exists] 表名 例如:

 drop table if exists test;

/关键字:alter 修改表名(改)/ alter table 旧表名 rename to 新表名;

/修改列定义/ /关键字:add 增加一列/ alter table 表名 add 新列名 字段类型 [字段选项]; 例如:

alter table test add name char(10) not null default '' comment '名字';

/关键字:drop 删除一列/ alter table 表名 drop 字段名; 例如:

alter table test drop content;

/关键字:modify 修改字段类型/ alter table 表名 modify 字段名 新的字段类型 [新的字段选项]; 例如:

alter table test modify name varchar(100) not null default 'admin' comment '修改后名字';

/关键字:first 修改字段排序,把某个字段放在最前面/ alter table 表名 modify 字段名 字段类型 [字段选项] first; 例如:

alter table test modify name varchar(100) not null default 'admin' comment '最前面' first;

/关键字:after 修改字段排序,字段名1放在字段名2的后面/ alter table 表名 modify 字段名1 字段类型 [字段选项] after 字段名2; 例如:

 alter table test modify name varchar(100) not null default 'admin' comment 'time字段后面' after time;

/关键字:change 重命名字段/ alter table 表名 change 原字段名 新字段名 新的字段类型 [新的字段选项] 例如:

alter table test change name username varchar(50) not null default '' comment '用户名字';

/修改表选项/ alter table 表名 表选项信息; 例如:

alter table test engine Myisam default charset gbk; --修改存储引擎和修改表的字符集