MySQL建库建表和修改表结构

来源:互联网 发布:数据库系统及其应用 编辑:程序博客网 时间:2024/05/22 12:02

创建数据库

create database databaseName;
一般使用:

drop database if exists databaseName;create database databaseName default character set utf8 collate utf8_general_ci;

删除数据库

drop database if exists databaseName;

创建表

create table tableName(id int(32) primary key,name varchar(128) default null);

一般使用:

drop table if exists tableName;create table tableName(id int(32) primary key not null auto_increment comment 'id,主键',`code` varchar(128) unique not null comment '唯一码',`status` enum('-1','0','1') not null default '0' comment '状态,-1未连接,0关,1开',recorded_date datetime not null comment '录入时间')engine=innodb default charset=utf8 comment='xx表';

删除表

drop table tableName;

修改表名

alter table oldTbleName rename newTableName;

添加列

alter table tableName add column columnName varchar(10);

添加列到指定列之后

alter table tableName add column columnName2 varchar(10) after columnName1;

删除列

alter table tableName drop column columnName;

修改列名

alter table tableName change column oldColumnName newColumnName varchar(10);

修改列类型(或修改列长度)

alter table tableName modify column columnName varchar(10);

alter table tableName modify columnName varchar(10);

添加主键

alter table tableName add primary key(id);

删除主键

alter table tableName drop primary key;

添加外键

alter table table1 add constraint foreignKeyName foreign key( table1_ColumnName) references table2(table2_PrimaryKeyColumnName);

删除外键

alter table table1 drop foreign key foreignKeyName;

添加自增

auto_increment必须要求该列是主键(或别的键,详细请看文章:http://blog.csdn.net/u012643122/article/details/52643888),所以
如果该列不是主键:
alter table tableName change columnName columnName int(16) not null primary key auto_increment;
如果该列是主键:
alter table tableName change columnName columnName int(16) not null auto_increment;

删除自增

alter table tableName change columnName columnName int(16);//删除自增长

0 0
原创粉丝点击