MYSQL有关表的操作

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43849107/article/details/85635995

MYSQL中有关表的一系列操作

  1. 创建数据库company
    create databae company;
  2. 创建两个表offices和employees:
    创建offices
    创建employees

代码如下:

creaate table offices(
officeCode varchar(10) NOT NULL UNIQUE,
city varchar(50) NOT NULL,
address varchar(50),
country varchar(50) NOT NULL,
postalCode varchar(15),
primary key (officeCode)
);

create table employees(
employeeNumber int(11) NOT NULL primary key auto_increment,
lastName varchar(50) NOT NULL,
firstName varchar(50) NOT NULL,
mobile varchar(25) unique,
officeCode varchar(10) NOT NULL UNIQUE,
jobTitle varchar(50) NOT NULL,
birth datetime NOT NULL,
note varchar(255),
sex varchar(5),
CONSTRAINT office_fk FOREIGN KEY(officeCode) REFERENCES offices(officeCode)
);
  1. 将employees中的mobile字段移动到officeCode后面
alter table employees modify mobile varchar(25) after officeCode;

使用 alter table 表名 modify 字段名 数据类型 after 字段名;

  1. 将employees中的birth改为employee_birth;
alter table employees change birth employee_birth datetime;

使用 alter table 表名 change 原字段名 现字段名 数据类型;

  1. 修改sex的字段类型,将sex的字段类型修改为char(1),非空约束;
alter table employees modify sex char(1) NOT NULL;

使用 alter table 表名 modify 字段名 现在的数据类型;

  1. 删除字段note
alter table employees drop note;

删除时使用drop
alter table 表名 drop 字段名;

  1. 增加字段favoriate_activity,数据类型为varchar(100);
alter table employees add favorite_activity varchar(100);

使用 alter table 表名 add 字段名 数据类型;

  1. 删除表offices(在创建表employees时,设置了外键,关联了父类officesofficeCode,
    所以要先删除employees的外键约束)
    1. 删除外键约束;
alter table employees drop foreign key office_fk;
  1. 删除表offices;
drop table offices;
  1. 将employees的表名修改为employees_info;
alter table employees rename employees_info;

猜你喜欢

转载自blog.csdn.net/weixin_43849107/article/details/85635995
今日推荐