数据库设计1-表约束(主键、自动增长、外键、级联),多表关系(实例)

数据库设计

1、表约束

对表中的数据进行限制,以保证数据的正确、完整、有效
分类:主键约束primary key 、非空约束not null、唯一约束unique、外键约束foreign key

主键约束

含义:非空且唯一

一张表只能有一个字段为主键
主键就是表中记录的唯一标识

自动增长

数值类型,使用auto_increment,可以实现值的自动增长

外键约束

语句:alter table 表名 constraint 外键名称 foreign key (外键字段) references 主表名称(主表列名称);
外键:在从表中与主表主键对应的那一列
主表: 一方,用来约束别人的表
从表: 多方,被别人约束的表

默认值

默认值 DEFAULT

级联操作

在设置外键的时候设置级联更新
alter table 表名 constraint 外键名称 foreign key (外键字段) references 主表名称(主表列名称) on updata cascade ;
on delete cascade 删除外键;
在修改和删除主表的主键时,同时更新或删除副表的外键值

2、多表之间的关系

多表之间的关系:
1对1;1对多;多对多;

1对多

实现:在多方建立外键来指向一方的主键

多对多

多对多关系建表原则: 需要创建第三张表,中间表(实现2个1对多)至少两个字段,这两个字段分别作为外键指向各自一方的 主键。

附上一个旅游网站的简易数据库及表关系设计实例:

--创建旅游类型表
create table tab_category (
  cid int primary key auto_increment,
  cname varchar(100) not null unique)

Insert into tab_category (cname) values ('周边游'), ('出境游'), ('国内游'), ('港澳游');
select * from tab_category;
--创建旅游线路表,其中类型列外键至类型表的cid列
create table tab_route(
  rid int primary key auto_increment,
  rname varchar(100) not null unique,
  price double,
  rdate date,
cid int,
  foreign key (cid) references tab_category(cid)
)
INSERT INTO tab_route VALUES
(NULL, '【厦门+鼓浪屿+南普陀寺+曾厝垵 高铁 3 天 惠贵团】尝味友鸭面线 住 1 晚鼓浪屿', 1499, '2018-01-27', 1),
(NULL, '【浪漫桂林 阳朔西街高铁 3 天纯玩 高级团】城徽象鼻山 兴坪漓江 西山公园', 699, '2018-02-22', 3),
(NULL, '【爆款¥1699 秒杀】泰国 曼谷 芭堤雅 金沙岛 杜拉拉水上市场 双飞六天【含送签费 泰风情 广州 往返 特价团】', 1699, '2018-01-27', 2),
(NULL, '【经典•狮航 ¥2399 秒杀】巴厘岛双飞五天 抵玩【广州往返 特价团】', 2399, '2017-12-23', 2),
(NULL, '香港迪士尼乐园自由行2天【永东跨境巴士广东至迪士尼去程交通+迪士尼一日门票+香港如心海景酒店 暨会议中心标准房1晚住宿】', 799, '2018-04-10', 4);
select * from tab_route;
--创建用户信息表
create table tab_user (
  uid int primary key auto_increment,
  username varchar(100) unique not null,
  password varchar(30) not null,
  name varchar(100),
birthday date,
sex char(1) default '男',
  telephone varchar(11),
  email varchar(100)
);
INSERT INTO tab_user VALUES
(NULL, 'cz110', 123456, '老王', '1977-07-07', '男', '13888888888', '[email protected]'), (NULL, 'cz119', 654321, '小王', '1999-09-09', '男', '13999999999', '[email protected]');
select * from tab_user;

--创建收藏页表
create table tab_favorite (
rid int,
date datetime,
uid int,
-- 创建复合主键,其中rid外键至tab_route(rid);uid外键至tab_user(uid)
primary key(rid,uid),
foreign key (rid) references tab_route(rid), foreign key(uid) references tab_user(uid)
)
	INSERT INTO tab_favorite VALUES
	(11, '2018-01-01', 1), -- 老王选择厦门 
	(12, '2018-02-11', 1), -- 老王选择桂林 
	(13, '2018-03-21', 1), -- 老王选择泰国 
	(12, '2018-04-21', 2), -- 小王选择桂林 
	(13, '2018-05-08', 2), -- 小王选择泰国 
	(15, '2018-06-02', 2); -- 小王选择迪士尼

猜你喜欢

转载自blog.csdn.net/weixin_52723971/article/details/112188360