database - 解决数据库关系循环
问题描述
客户可以租车或出租汽车。如您所见,汽车有 OwnerID - 拥有汽车的客户,但同时客户也可以从其他所有者那里租用汽车,因此在订单表中他显示为用户。
那么我怎样才能改变模型来避免这样的循环,甚至有可能吗?
解决方案
考虑识别(存储在表格中)
- 所有者是谁以及他们拥有什么,以及
- 客户是谁。
.
create table persons (
-- I prefer "people". YMMV.
person_id integer primary key,
person_name varchar(25) not null
-- Other columns go here.
);
create table cars (
-- VIN might be a better choice.
car_id integer primary key
-- Other columns go here.
);
create table car_owners (
-- Only car owners known to us can rent out a car.
car_id integer not null
references cars(car_id),
owner_id integer not null
references persons (person_id),
primary key (car_id, owner_id)
-- Other columns go here.
);
create table customers (
-- Any person can rent a car. (But some persons are not customers.)
customer_id integer primary key
references persons (person_id)
-- Other columns go here.
);
create table rentals (
customer_id integer not null
references customers (customer_id),
car_id integer not null,
owner_id integer not null,
primary key (customer_id, car_id, owner_id),
-- Don't rent a car unless we know who the owner is.
foreign key (car_id, owner_id)
references car_owners (car_id, owner_id)
-- Other columns go here.
);
推荐阅读
- javascript - 从 javascript 数组生成可点击的 HTML 链接
- javascript - 从 Array Javascript 中的某些对象中获取随机项
- python - 为什么这个 Python-CAN 脚本的频率发生了变化?
- time - 当我使用 Date Add 时,Dax 给了我 2 个截然不同的答案
- python - 如何在 AWS Sagemaker 中通过 Conda 指定和安装最新版本的 PyTorch?
- javascript - 如何使用占位符制作像文本框一样的输入框以输入密码?
- ubuntu-18.04 - 无法在 schroot 中找到 JAVA
- react-native - 如何在功能组件内处理来自 reducer 的返回值
- azure - 尝试为 Azure 函数部署事件网格订阅时出现 InvalidResourceNamespace 错误
- excel - 通过运行相同的 VBA 增大 Excel 工作簿的大小