在数据库中实现相互关联的元组的最佳方法,例如零件交换汽车

Best way to Implement interrelated tuple sin a database, such as Part Exchange cars

我正在设计一个汽车经销商管理系统,我有以下实体:

汽车,销售,购买,卖方,买方,费用。他们之间的关系是直截了当的;一辆汽车可以有很多费用,但一次销售和一次购买。一次销售可以有一个买家,一次购买可以有一个卖家。

麻烦在于实施零件交换车辆。这些基本上是彼此相关且属于同一车辆 table:当一辆汽车被出售时,它可以有现金价格、卡价格或分配给它的零件交换价格,这基本上是 value/money 经销商已收到付款。这意味着可以在同一 table 中为使用另一辆车支付一辆车的费用。但我不想为每辆车都创建一个零件交换价格字段,因为这种情况很少见。

在同一个 table 中建立此类连接的最佳方式是什么,以便我可以查询 "What are all the cars that were sold on a part exchange basis and what cars did i receive in exchange for them"

之类的内容

如果我需要澄清一些事情,请告诉我:)

使用 junction table,将 Cars 与其自身相关联,将 table 称为 CarPartExchange 之类的东西,其中包含以下列:

  • SoldCarId - 对已售出汽车的引用,
  • ExchangeCarId - 对已交换的汽车的引用,并且
  • PartExchangePrice - 用于交换的价格。

What are all the cars that were sold on a part exchange basis

select SoldCarId from CarPartExchange;

and what cars did i receive in exchange for them

select SoldCarId, ExchangedCarId from CarPartExchange
inner join Car SoldCar on SoldCar.Id = CarPartExchange.SoldCarId
inner join Car ExchangedCar on ExchangedCar.Id = CarPartExchange.ExchangedCarId
where PartExchangePrice > 100;

如果您想在结果中包含来自汽车 table 的信息,则上述示例中的连接是必需的。我正在使用任意示例查找价格大于 100 的所有交易所。