MySQL如何在没有公共密钥的情况下加入3个表

时间:2015-05-03 17:19:18

标签: mysql sql select join

我有三张桌子,我需要加入如下。

 INVENTORY
 BOOK_CODE, BRANCH_NUM, ON_HAND

 BOOK
 BOOK_CODE, TITLE

 AUTHOR
 AUTHOR_NUM, AUTHOR_LAST

基本上,我需要从分支4(在库存中)中选择所有书籍的作者姓名,书名和现有计数。问题是,必须通过第四个表格来访问AUTHOR表。

 WROTE
 BOOK_CODE, AUTHOR_NUM

如果所有表都有BOOK_CODE,我可以轻松完成,但我无法弄清楚如何将其全部插入到一个查询中。我尝试过以下方法:

 SELECT TITLE, AUTHOR_LAST, ON_HAND
 FROM BOOK, AUTHOR, INVENTORY
 WHERE BOOK.BOOK_CODE = INVENTORY.BOOK_CODE
 AND AUTHOR_NUM IN
 (SELECT AUTHOR_NUM
 FROM WROTE
 WHERE WROTE.BOOK_CODE = INVENTORY.BOOK_CODE)
 AND BRANCH_NUM='4';

但是这会返回错误的字段,所以我不知道自己做错了什么。

1 个答案:

答案 0 :(得分:1)

您可以“链接”您的联接:

SELECT title, author_last, on_hand
FROM   book b
JOIN   inventory i ON b.book_code = i.book_code
JOIN   wrote w ON b.book_code = w.book_code
JOIN   author a ON a.author_num = w.author_num
WHERE  branch_num = 4