MYSQL数据库表与表之间的关系
- 一 对 一 关联关系 :
- 主键 + 外键 + unique
create table tb_user_info( id bigint primary key auto_increment , realName varchar(20) comment '真实姓名', cardNo varchar(18) comment '身份证号' , photo varchar(100) comment '用户头像' , birth date comment '出生日期' , user_id bigint unique comment '用户ID', -- 添加一个外键约束 constraint tb_user_info_user_id_fk foreign key(user_id) references tb_user(id) );
- 共享主键
create table tb_user_info( id bigint primary key , realName varchar(20) comment '真实姓名', cardNo varchar(18) comment '身份证号' , photo varchar(100) comment '用户头像' , birth date comment '出生日期' , -- 添加一个外键约束 constraint tb_user_info_user_id_fk foreign key(id) references tb_user(id) );
- 一 对 多 关联关系 :
create table tb_address ( id bigint primary key auto_increment , name varchar(50) comment '收货人', pro varchar(20) comment '省份', city varchar(20) comment '城市', country varchar(20) comment '区县', detail varchar(50) comment '详细地址', tel varchar(11) comment '联系方式' , user_id bigint comment '用户ID' , -- 添加外键约束 foreign key(user_id) references tb_user(id) );
- 多 对 多 关联关系 :
create table tb_role( id bigint primary key auto_increment , name varchar(100) comment '角色名' , description text comment '角色描述' );
- 中间表 + 2个外键 + 主键
create table tb_role_user( id bigint primary key auto_increment , role_id bigint comment '角色Id', user_id bigint comment '用户ID', foreign key(role_id) references tb_role(id), foreign key(user_id) references tb_user(id) ) ;
- 中间表 + 2 个外键 + 联合主键
create table tb_role_user( role_id bigint comment '角色Id', user_id bigint comment '用户ID', foreign key(role_id) references tb_role(id), foreign key(user_id) references tb_user(id), -- 联合主键 primary key(role_id, user_id) ) ;
- 中间表 + 2个外键 + 主键