解决数据库关系周期

问题描述 投票:-1回答:2

在数据库中,我有一个类型的模型:enter image description here

顾客可以租车或租车。如您所见,Car拥有OwnerID - 拥有汽车的客户,但同时客户也可以从其他所有者那里租车,以便在Order表中他显示为User。 那么我怎样才能改变模型以避免这种循环,甚至可能呢?

database database-design foreign-keys database-relations
2个回答
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.
);

0
投票

根据我的理解,我认为最好为所有者(出租汽车的人)和租户(出租汽车的人)提供两个单独的档案,并有单独的登录

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

希望这对你有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.