[英]Is it ok to reference two foreign keys when the primary key is in a different table?
Author( AuthorID , AuthorName, Address, TelephoneNo, PublisherCode )作者( AuthorID , AuthorName, Address, TelephoneNo, PublisherCode )
Book ( BookID , Name, ReleaseDate, Price, AuthorID )图书(书名、名称、发行日期、价格、作者ID )
Publisher( PublisherID , Name, Address, AuthorID )出版商(出版商ID ,姓名,地址,作者ID )
PK = Bold PK = 粗体
FK = Italic FK = 斜体
I am trying to write a query which我正在尝试编写一个查询
Will illustrate the books and their various Publishers and group by PublisherID
将说明书籍及其各种出版商并按 PublisherID 分组
I get the general idea of retrieving this information but I would like to know if it is ok to references a FK to another FK.我大致了解了检索此信息,但我想知道将 FK 引用到另一个 FK 是否可以。
For example book.AuthorID = publisher.AuthorID
as the PK AuthorID is not in either of the tables in the query.例如
book.AuthorID = publisher.AuthorID
作为 PK AuthorID 不在查询的任何一个表中。
SELECT b.name. p.name
FROM Books b
INNER JOIN Publisher p ON b.authorID = p.publisherID
GROUP BY publisherID
I think with "FK to another FK" you mean getting PublisherCode (book(authorID) -> Author(PublisherCode) -> Publisher).我认为“FK 到另一个 FK”是指获得 PublisherCode (book(authorID) -> Author(PublisherCode) -> Publisher)。
I wouldn't do it cuz Publisher is a property of the book, not of the Author, therefore you should store the PublisherID reference in you Book table我不会这样做,因为Publisher是书的属性,而不是作者的属性,因此您应该将 PublisherID 引用存储在您的 Book 表中
Book (BookID, Name, ReleaseDate, Price, AuthorID, PublisherID)
Also if you store PublisherID within Book table, it will allow only one publisher, since the query you are required for is to show "the various Publishers" of each book, you should use another table to represent that interaction此外,如果您将 PublisherID 存储在 Book 表中,它将只允许一个出版商,因为您需要的查询是显示每本书的“各种出版商”,您应该使用另一个表来表示该交互
BookXPublisher (BookFK, PublisherFK)
This table only have two Foreign Keys, and will store data like this这个表只有两个外键,会像这样存储数据
(1 , 1) BookID:1 && PublisherID:1
(1 , 2) BookID:1 && PublisherID:2
(3 , 1) BookID:3 && PublisherID:1
You can add another table for BookXAuthor to the same purpose您可以为 BookXAuthor 添加另一个表以达到相同目的
With that in mind you query will be考虑到这一点,您的查询将是
SELECT b.name. p.name
FROM Books b
INNER JOIN BookXPublisher bxp ON b.BookID = bxp.BookFK
INNER JOIN Publisher p ON p.PublisherID = bxp.PublisherFK
And your tables like this:你的表是这样的:
Book ( BookID , Name, ReleaseDate, Price)书(书名,名称,发行日期,价格)
Publisher( PublisherID , Name, Address)出版商(出版商ID ,名称,地址)
BookXPublisher ( BookFK , PublisherFK ) BookXPublisher ( BookFK , PublisherFK )
Additionally, with GROUP BY
you can count how many books have published a author oa Publisher此外,使用
GROUP BY
您可以计算一个作者 oa 出版商出版了多少本书
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.