数据库架构问题

发布于 2024-10-23 21:01:40 字数 121 浏览 2 评论 0原文

如果我使用一个表的主键作为另一个表的主键,它仍然是外键吗?

例如,

两个表album 和特价商品

AlbumId 是两者的主键

我如何使用主键外键表示法表示此关系?

If I use the primary key of a table as the primary key of another table is it still a foreign key?

e.g.

Two tables albums and special offers

AlbumId is the primary key in both

How do I represent this relation using primary key foreign key notation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

远山浅 2024-10-30 21:01:40

是的,它仍然是主键。它通常称为一对一关系。

你可以这样做:

create table albums (
    album_id integer primary key,
    -- other fields...
);

create table special_offers (
    album_id integer primary key references albums(album_id),
    -- other fields...
);

Yes, it's still a primary key. It's usually called a one-to-one relation.

You can do something like:

create table albums (
    album_id integer primary key,
    -- other fields...
);

create table special_offers (
    album_id integer primary key references albums(album_id),
    -- other fields...
);
从﹋此江山别 2024-10-30 21:01:40

例如,如果您对同一专辑有多个特价商品,AlbumId 在特价商品表中不再是唯一的。
我会考虑添加 SpecialOfferId 并设计一对多关系。

if e.g you have several special offers for the same album AlbumId is no longer unique in the special offers table.
I would think about adding a SpecialOfferId and design a one-to-many relation.

〃温暖了心ぐ 2024-10-30 21:01:40

巴勃罗·圣克鲁斯是对的——是的,你可以这样做。然而,从哲学上来说,只有真正存在一对一的关系才有意义——所有专辑都有且只有一张特价商品,并且所有特价商品都有且只有一张专辑。

从您的问题域猜测,情况并非如此 - 有些专辑没有特别优惠,有些有 1 个,有些有很多。

如果确实如此,bw_üezi 是对的 - 创建一对多关系。

create table albums (
    album_id integer primary key,
    -- other fields...
);

create table special_offers (
    special_offer_id integer primary key,
    album_id integer foreign key references albums(album_id),
    -- other fields...
);

Pablo Santa Cruz is right - yes, you're allowed to do this. However, philosophically, it's only meaningful if there really is a one-to-one relationship - all albums have one and only one special offer, and all special offers have one and only one album.

Guessing from your problem domain, that's not the case - some albums have no special offers, some have 1, some have many.

If that is indeed true, bw_üezi is right - create a one-to-many relationship.

create table albums (
    album_id integer primary key,
    -- other fields...
);

create table special_offers (
    special_offer_id integer primary key,
    album_id integer foreign key references albums(album_id),
    -- other fields...
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文