MySQL表操作

字段操作

create table tf1(
	id int primary key auto_increment,
    x int,
    y int
);

# 修改
alter table tf1 modify x char(4) default '';
alter table tf1 change y m char(4) default '';

# 增加
mysql>: alter table 表名 add 字段名 类型[(长度) 约束];  # 末尾
eg>: alter table tf1 add z int unsigned;

mysql>: alter table 表名 add 字段名 类型[(宽度) 约束] first;  # 首位
eg>: alter table tf1 add a int unsigned first;

mysql>: alter table 表名 add 字段名 类型[(宽度) 约束] after 旧字段名;  # 某字段后
eg>: alter table tf1 add xx int unsigned after x;

mysql>: alter table 表名 drop 字段名;  # 删除字段
eg>: alter table tf1 drop a;

表与表关系

  • 一对一
  • 一对多
  • 多对多
定义:通过外键将两张表进行连接。

一对一

#################
###创建学生详情表##
#################                 
create table student_author(id int primary key auto_increment,
                     info varchar(256),
    				 address varchar(256)
                    );
#############
###创建学生表##
#############
create table student(
	id int primary key auto_increment,
    name varchar(64) not null,
    mobile char(11) unique not null,
    sex enum('男', '女') default '男',
    age int default 0,
    author_id int unique not null,
    foreign key(author_id) references student_author(id)
    on update cascade 
    on delete cascade
);

一对多

##############
###创建国家表##
##############
create table state(id int primary key auto_increment,
                  name varchar(20) not null unique
                  );
##############
###创建学生表##
##############                  
create table student(id int primary key auto_increment,
                     name varchar(16) not null,
                     sex enum('男','女'),
                     state_id int,
                     foreign key(state_id) references state(id)
                     on update cascade
                     on delete cascade
                    );
##############
###插入国家信息##
##############      
insert into state(name) values('中国'),('日本'),('美国');

多对多

##############
###创建学生表##
#############
create table student(
	id int primary key auto_increment,
    name varchar(64) not null,
    mobile char(11) unique not null,
    sex enum('男', '女') default '男',
    age int default 0
);
##############
###创建课程表##
#############
create table course(
    id int primary key auto_increment,
    name varchar(64) not null
);
####################
###创建学生课程关系表##
####################
create table student_course(
    id int primary key auto_increment,
    student_id int,
    foreign key(student_id) references student(id)
    on update cascade
    on delete cascade,
    couorse_id int,
    foreign key(couorse_id) references course(id)
    on update cascade
    on delete cascade,
    unique(student_id, couorse_id)
);
原文地址:https://www.cnblogs.com/ledgua/p/11586641.html