Sql查询Join / Where 3 Tables

时间:2017-12-13 19:55:22

标签: mysql sql

我遇到了一些问题。

我目前有3张桌子:

BOOK
Book_Num
Title
Publisher_Code

AUTHOR
Author_Num
Author_Fname
Author_Lname

WROTE
Book_Code
Authour_Num
Sequence

我需要一个列出John Steinbeck编写的所有书籍的查询。因此我需要加入表格,但是我很难加入连接并且遇到了一些困难。

这是我到目前为止的查询:

`SELECT W.BOOK_CODE, W.AUTHOR_NUM , B.TITLE, A.AUTHOR_LAST
    FROM WROTE W
    JOIN BOOK B ON W.BOOK_CODE = B.BOOK_CODE
    JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_LAST
    WHERE A.AUTHOR_LAST = "Steinbeck"
    ORDER BY A.AUTHOR_LAST;
`

目前它只显示一个空集,但该字段肯定存在。

3 个答案:

答案 0 :(得分:2)

我相信你的问题在这里:

JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_LAST

应该是

JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_NUM

此外,您似乎正在使用B.BOOK_CODE当您应该使用B.BOOK_NUM

这应该适合你:

SELECT W.BOOK_CODE, W.AUTHOR_NUM , B.TITLE, A.AUTHOR_LAST
FROM WROTE W
JOIN BOOK B ON W.BOOK_CODE = B.BOOK_NUM
JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_NUM
WHERE A.AUTHOR_LAST = "Steinbeck"
ORDER BY A.AUTHOR_LAST;

答案 1 :(得分:0)

我认为问题在于这一行:

JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_LAST

您正在将写入表中的Author_Num加入Author表中的Author_Last。

试试这个: JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_NUM

答案 2 :(得分:0)

SELECT W.BOOK_CODE, W.AUTHOR_NUM , B.TITLE, A.AUTHOR_LAST
FROM WROTE W
JOIN BOOK B ON W.BOOK_CODE = B.BOOK_CODE
JOIN AUTHOR A ON W.AUTHOR_NUM = A.AUTHOR_LAST --its wrong 
-- it must A.Author_Num
WHERE A.AUTHOR_LAST = "Steinbeck"
ORDER BY A.AUTHOR_LAST

您必须与PK主键和foreing键关联。