【MySQL】库&表的基本操作

数据库的基本操作

create database 数据库名称;

show create database db1;

drop database db1;

alter database db1 character set gbk;

切入

use db1;

查看当前使用数据库

select database();

数据表的基本操作

注意:在操作数据表之前应使用“USE 数据库名;”

create table 表名(
         字段1 字段类型,
         字段2 字段类型,
         …
         字段n 字段类型
);

查所有表

show tables;

查指定表

show create table student;
# student是具体表明

查表字段信息

desc student;

删表

drop table 表名;

改表名

alter table student rename to stu;

改字段名

alter table stu change name sname varchar(10);

改字段属性

alter table stu modify sname int;

增字段

alter table stu add address varchar(50);

删字段

alter table stu drop address;

数据表的约束

为防止错误的数据被插入到数据表,MySQL中定义了一些维护数据库完整性的规则;

以下五种约束条件针对表中字段进行限制从而保证数据表中数据的正确性和唯一性。换句话说,表的约束实际上就是表中数据的限制条件。

约束条件 说明
PRIMARY KEY 主键约束用于唯一标识对应的记录
FOREIGN KEY 外键约束
NOT NULL 非空约束
UNIQUE 唯一性约束
DEFAULT 默认值约束,用于设置字段的默认值

主键约束(PRIMARY KEY)

主键约束即primary key用于唯一的标识表中的每一行。被标识为主键的数据在表中是唯一的且其值不能为空。

  • 基本语法

    字段名 数据类型 primary key;

  • 示例一

    create table student(
      id int primary key,
      name varchar(20)
    );
    
  • 示例二

    create table student01(
      id int,
      name varchar(20),
      primary key(id)
    );
    

非空约束(NOT NULL)

指的是字段的值不能为空

  • 基本语法

    字段名 数据类型 NOT NULL;

  • 示例

    create table student02(
      id int,
      name varchar(20) not null
    );
    

默认值约束(DEFAULT)

用于给数据表中的字段指定默认值,即当在表中插入一条新记录时若未给该字段赋值,那么,数据库系统会自动为这个字段插人默认值

  • 基本语法

    字段名 数据类型 DEFAULT 默认值;

  • 示例

    create table student03(
      id int,
      name varchar(20),
      gender varchar(10) default 'male'
    );
    

唯一性约束(UNIQUE)

用于保证数据表中字段的唯一性,即表中字段的值不能重复出现

  • 基本语法

    字段名 数据类型 UNIQUE;

  • 示例

    create table student04(
      id int,
      name varchar(20) unique
    );
    

外键约束(FOREIGN KEY)

用于多张表之间的约束

  • 基本语法

    – 在创建数据表时语法如下:
    CONSTRAINT 外键名 FOREIGN KEY(从表外键字段) REFERENCES 主表(主键字段)
    – 将修改数据表时语法如下:
    ALTER TABLE 从表名 ADD CONSTRAINT 外键名 FOREIGN KEY(从表外键字段) REFERENCES 主表(主键字段);

  • 示例一

    create table student05(
      id int primary key,
      name varchar(20)
    );
    create table class(
      classid int primary key,
      studentid int,
      constraint fk_class_studentid foreign key(studentid) references student05(id)
    );
    
  • 示例二

    create table student05(
      id int primary key,
      name varchar(20)
    );
    create table class(
      classid int primary key,
      studentid int
    );
    alter table class 
    	add constraint fk_class_studentid foreign key(studentid) references student05(id);
    

删除外键

  • 语法

    alter table 从表名 drop foreign key 外键名;

  • 示例

    alter table class drop foreign key fk_class_studentid;
    

注意细节

  • 从表里的外键通常为主表的主键
  • 从表里外键的数据类型必须与主表中主键的数据类型一致
  • 主表发生变化时应注意主表与从表的数据一致性问题

猜你喜欢

转载自blog.csdn.net/al6nlee/article/details/131154051