mysql学习笔记(一)----建表操作

my建表操作

创建表

    create Table <表名>
    (
        字段名1,数据类型 [列级约束] [默认值],
        字段名2,数据类型 [列级约束] [默认值],
        ...
        [表级约束],
        [constraint <约束名> ...]
    );

    Eg:
        create table a
        (
            id int(11),
            name varchar(255),
            salary float
        );

添加列级约束 / 表级约束

    Eg1://列级约束
        create table a
        (
            id int(11) primary key auto_increment,
            name varchar(255) not null default '',
            telNumber varchar(255) Unique
        );
        //auto_incrementy一个表只能有一个字段使用,并且这个字段必须为主键的一部分

    Eg2://表级约束
        create table b
        (
            id int(11),
            name varchar(255),
            telNumber varchar(255),
            constraint fk foregin key (telNumber) reference a(telNumber),
            constraint primary key (id,name),
            constraint unique_con Unique(telNumber),
            constraint unique_name_con Unique(name),
        )

查看表的信息

查看表数据结构

DESCRIBE 表名
或
DESC 表名

查看表详细结构语句(建表语句,包括存储引擎和字符编码)

show create table <表名G>;//不加 "G" 参数,显示结果可能会非常混乱.

Eg:
show create table aG;

修改表名

alter table a rename to c;

修改字段数据类型

 alter table <表名> modify <新字段名> <数据类型>

 alter table a modify name int(10);

修改字段名

alter table <表名> change <旧字段名> <新字段名> <新数据类型>

alter table a change name vname varchar(10)

添加字段

alter table <表名> add <新字段名> <数据类型> [约束条件] [first |(after 已存在的字段名)];

alter table a add age int(10) not null default 0 first;

alter table a add pid int(10) not null auto_increment default 0 after id;

删除字段

alter table <表名> drop <字段名>

alter table a drop vname;

修改字段的排列位置

alter table <表名> modify <字段1> <数据类型> first|after <字段2>;

alter table a modify name varchar(255) first;

alter table a modify nam varchar(255) abfter telNumber;

更改表的存储引擎

引擎名 是否支持
FEDERAted
MRG_MYISAM
MyISMA
BLACKHOLE
CSV
MEMORY
ARCHIVE
InnoDB 默认
PERFORMANCE_SCHEMA
alter table <表名> ENGINE=<更改后的存储引擎名>;

alter table a ENGINE=MyISAM;

删除表的外键约束

alter table <表名> drop foregin key <外键约束名>;

alter table a drop foregin key fk;

删除数据表

drop table [if exits] 表名1, 表名2,... 表名n;

drop table if exits a;

删除被其他表关联的主表

数据表之间存在外键关联的情况下,如果直接删除父表,结果会显示失败。原因是直接删除,将破坏表的参照完整性。如果必须要删除,可以先删除与它关联的子表,在删除父表,只是这样同时删除了两个表中的数据。但是有的情况下可能要保留子表,这时如要单独的删除父表,只需将关联表的外键约束条件取消,然后就可以删除父表。

Tips

虽然可以指定表的存储引擎,但是不同存储引擎的表之间不能建立外键约束

原文地址:https://www.cnblogs.com/hlere/p/6206858.html