【问题标题】:Resolve the database relationship cycle解决数据库关系循环
【发布时间】:2019-09-03 22:37:06
【问题描述】:

在数据库中,我有一个模型:

客户可以租车或出租汽车。如您所见,汽车有 OwnerID - 拥有汽车的客户,但同时客户也可以从其他所有者那里租用汽车,因此在订单表中他显示为用户。
那么如何更改模型以避免这样的循环,甚至有可能吗?

【问题讨论】:

  • 客户可以从您的企业租用,而不是从车主那里租用吗?每个客户都必须是车主吗?
  • use text, not images/links, for text--including tables & ERDs. 仅将图像用于无法表达为文本或扩充文本的内容。无法搜索或剪切和粘贴图像。在图像中包含图例/键和说明。让您的帖子自成一体。
  • 那么一个用户是一个客户是一个租客?您不能称用户为租户或租户为用户吗? PS循环有什么问题&什么是循环&这里的循环是什么? (您的箭头不会形成有向循环。)
  • 那么一个用户是一个客户是一个租客?您不能称用户为租户或租户为用户吗? PS循环有什么问题&什么是循环&这里的循环是什么? (您的箭头不会形成有向循环。) PS 鉴于您的规范(有合理假设),此设计没有任何问题,实际问题是您有错误的期望/概念。告诉我们你是从什么假设中推理出来的。你可能是对的,所以我们需要验证一些东西;但你碰巧弄错了,所以我们会揭穿它。

标签: database database-design foreign-keys database-relations


【解决方案1】:

考虑识别(存储在表格中)

  • 所有者是谁以及他们拥有什么,以及
  • 客户是谁。

.

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.
);

【讨论】:

  • 这并没有解决问题,因为问题设计包含在此设计中。问题设计本身并没有错,提供更复杂的设计也无济于事,而且您没有解决他们的问题及其误解。
【解决方案2】:

根据我的理解,我认为最好为所有者(出租汽车的人)和租户(租用汽车的人)设置两个单独的个人资料并分别登录

User      Owner      Tenant     Order
------    ------     -------    -------    
id        owner_id   tenant_id  owner_id 
email     user_id    user_id    tenant_id 
                                car_id

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2013-08-23
    • 2018-10-13
    相关资源
    最近更新 更多