DDL解释
DDL是Data Definition Language的缩写,主要包括create、alter、drop等常用指令,用于操作表或者数据库结构的指令。
数据库
创建数据库
create database dbName default charset utf8 collate utf8_general_ci;
使用数据库
use dbName;
删除数据库
drop database dbName;
数据表
创建表
create table if not exists tableName (column_name column_type); #案例 CREATE TABLE if not exists student ( id INT ( 10 ), user_name VARCHAR ( 50 ) ); #注释 默认值 主键 CREATE TABLE if not exists student ( id INT ( 5 ) NOT NULL PRIMARY KEY COMMENT '主键', user_name VARCHAR ( 20 ) COMMENT '账号', age INT ( 2 ) COMMENT '年龄' DEFAULT 18 ) COMMENT = '用户表';
删除表
drop table tableName; #案例 drop table student ;
添加列
alter table tableName add column_name column_type; #案例 ALTER TABLE student ADD age INT ( 3 );
删除列
alter table tableName drop column column_name; #案例 alter table student drop column age ;
修改列
alter table tableName modify column column_name column_type; alter table tableName change old_column_name new_column_name column_type; #案例 #修改字段类型 注释 ALTER TABLE student MODIFY COLUMN id INT ( 15 ) COMMENT 'id'; #修改字段名称 ALTER TABLE student CHANGE COLUMN age user_age VARCHAR ( 20 ); #修改字段为不可为空 ALTER TABLE student CHANGE id id INT NOT NULL; #添加主键 alter table student add primary key(id); #删除主键 alter table student drop primary key; alter table student modify id INT ( 15 ), drop primary key; ## 联合主键 一个主键可以是一个字段也可以是多个字段 ALTER TABLE t_user add CONSTRAINT pk_t_user_id PRIMARY KEY (id,user_name); #添加外键,stable从表名称,fk_name外键名称,fk外键,mtable主表名称,pk主键字段 alter table stable add constraint fk_name(如:FK_从表_主表) foreign key stable(fk) references mtable(pk); # 删除外键 alter table tableName drop foreign key fk_name # 修改默认值,default_value默认值 alter table tableName alter column_name set default default_value; #删除默认值 alter table tableName alter column_name drop default;
索引
创建索引
CREATE INDEX indexName ON table_name (column_name) #案例 create index indexName ON t_student(age);
删除索引
drop index indexName ON tableName;
创建唯一索引
create unique index indexName ON tableName(column_name); #案例 create unique index uniqueName ON t_student(age);
使用索引
添加主键,column_list主键列表,因为主键可以是多个
alter table tableName add primary key (column_list); #案例 alter table t_student add primary key (id,age);
创建唯一索引
alter table tableName add unique (column_list); #案例 alter table t_student add unique (id,age);
修改表结构,添加索引(普通索引)
alter table tableName add index indexName(column_list); #案例 alter table t_student add index indexId(id);
添加全文索引
alter table tableName add fulltext indexName(column_list); #案例 alter table t_student add fulltext fullName(name);
删除索引
alter table tableName drop index indexName; #案例 alter table t_student drop index fullName;
删除主键
alter table t_student drop primary key;
重置数据库表自增序列,id为主键
alter table tableName drop id; alter table tableName add id int unsigned not null auto_increment first,add primary key (id);
指定自增序列开始值
alter table tableName auto_increment = 100;