创建数据库market

  1. create schema market;
  2. use market;

创建表customers,在c_num添加主键约束和自增约束c_birth添加非空约束

create table customers(
c_num int(11) primary key not null unique auto_increment,
c_name varchar(50),
c_contact varchar(50),
c_city varchar(50),
c_birth datetime not null
);

插入c_contact到c_birth后面

alter table customers modify c_contact [varchar(50)] after c_birth; # 要加上数据类型

c_name字段数据类型改为varchar70

alter table customers change c_name varchar(70); # 用modify

c_contract 改为 c_phone

alter table customers change c_contact c_phone varchar(50);

增加c_gender char1

alter table customers add c_gender char(1);

修改表名customers_info

alter table customers rename customers_info;

删除c_city

alter table customers_info drop c_city;

修改存储引擎myisam

alter table customers_info engine=myisam; # 引擎engien单词拼写错误

创建表orders,在o_num上添加主键和自增,c_id添加外键关联c_num

create table orders (
o_num int(11) primary key not null unique auto_increment,
o_date date,
c_id varchar(50),
constraint fk_oc foreign key(c_id) references customers_info(c_num)
);

# 无法关联,查找原因为c_id varchar(50)和c_num int(11)的数据类型不一致导致错误。
# 改为 o_num 或 c_id 为 int 即可完成后续操作。

使用手册摘录[https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html]: Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same. 翻译:

外键和引用键中的相应列必须具有相似的数据类型。 整数类型的大小和符号必须相同。 字符串类型的长度不必相同。 对于非二进制(字符)字符串列,字符集和排序规则必须相同。

删除外键,删除表customers_info

alter table orders drop foreign key fk_oc;

drop table customers_info;