我想在MySQL中加入五个表

时间:2014-02-25 04:14:49

标签: mysql

图书

  • bookid(PK)
  • 标题

作者

  • 创作(PK)
  • AUTHORNAME

出版商

  • pubid(PK)
  • pubname

bookauthors

  • bookid(FK)
  • AUTHORID

bookpublisher

  • bookid(FK)
  • 发布商ID

我想加入所有五个表并获取这些列值:

  • BOOKID
  • 标题
  • AUTHORNAME
  • pubname

我应该只获得一行查询以获得上述结果。我写的是:

select books.*, authors.authorname
from authors,books
inner join bookauthors on books.bookid = bookauthors.bookid
inner join publisherbook on books.bookid = publisherbook.bookid
where books.bookid = 459567;

但相反,我得到了许多重复数据的行。

1 个答案:

答案 0 :(得分:3)

您需要为所有表使用联接。在FROM子句中使用多个表会生成笛卡尔积。试试这个

SELECT books.bookid, books.title, books.price, authors.authorname
FROM books
INNER JOIN bookauthors ON books.bookid = bookauthors.bookid
INNER JOIN publisherbook ON books.bookid = publisherbook.bookid
INNER JOIN authors ON bookauthors.authorid = authors.authorid -- assuming you meant authorid and not authored
WHERE books.bookid = 459567;

当然,如果您的图书有多位作者,那么在您的结果集中获得多行。

我不确定您为什么要加入publisherbook(或原始列表中的bookpublisher),除非您只是确保您的图书有出版商。同样,多个发布商会产生更多(重复)结果。

如果您只是想确保您的图书至少有一个发布商,请尝试使用此代码...

SELECT books.bookid, books.title, books.price, authors.authorname
FROM books
INNER JOIN bookauthors ON books.bookid = bookauthors.bookid
INNER JOIN authors ON bookauthors.authorid = authors.authorid -- assuming you meant authorid and not authored
WHERE EXISTS (
    SELECT 1 FROM publisherbook
    WHERE publisherbook.bookid = books.bookid
) AND books.bookid = 459567;