gpt4 book ai didi

mysql - 在一个表中有三个主键,其中两个是外键是否有意义?

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:46 26 4
gpt4 key购买 nike

我创建了一个包含三个表的数据库:

Restaurant
restaurant_id (autoincrement, PK)

Owner
owner_id (autoincrement, PK)
restaurant_id (FK to Restaurant)

Deal
deal_id (autoincrement)
owner_id (FK to Owner)
restaurant_id (FK to Restaurant)
(PK: deal_id, owner_id, restaurant_id)

每家餐厅可以有多个所有者。我为交易选择了两个外键,因此我可以引用所有者或餐厅的交易。交易表将具有三个主键,其中两个是外键。它将有两个指向它的一对多关系。我所有的外键都是主键,我不知道以后这样做会不会后悔。这个设计是否有意义,并且看起来对我想要实现的目标有好处?

Edit: What I really need to be able to accomplish here is when a owner is logged in and viewing their account, I want them to be able to see and edit all the deals that are associated with that particular restaurant. And because there can be more that one owner per restaurant, I need to be able to perform a query something like: select *from deals where restaurant_id = restaurant_id. In other words, if I'm an owner and I'm logged in, I need to be able to make query: get all of the deal that are related to not just me, the owner, but to all of the owners associated with this restaurant.

最佳答案

您在术语方面遇到了一些问题。

一个表只能有一个一个主键。不可能创建具有两个不同主键的表。您可以创建一个表,其中包含两个不同的唯一 索引(这很像主键),但只能存在一个主键。

您要问的是您是否应该拥有复合复合 主键;使用多个列的主键。

您的设计没问题,但如所写,您可能不需要 deal_id 列。在我看来,restaurant_id 和 owner_id 一起足以唯一标识 Deal 中的一行。 (如果一个所有者由于资本重组或收购另一个所有者而可以在一家餐馆拥有两种不同的所有权股份,那么这可能不是真的,但您在问题陈述中没有提到类似的事情)。

在这种情况下,deal_id 在很大程度上浪费了存储空间。 可能如果您有许多表有指向 Deal 的外键,或者如果您有要向用户显示多个 Deals 的实例,则可以使用 deal_id 列餐馆 老板。

如果其中一个论据使您决定采用 deal_id 列,那么它,而且只有它,应该是主键。包含其他两列不会添加任何内容,因为自动增量值本身是唯一的。

关于mysql - 在一个表中有三个主键,其中两个是外键是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10628552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com