如何在MySQL中进行此查询,我应该使用左连接还是右连接或内连接?

时间:2013-09-04 05:48:12

标签: mysql sql database join

table book:
BookCode| AuthorShortN  |Title
============================================
101 | Anton B   | THe Book of Leaves
102 | JJ. Abram | Wish Upon A Star
103 | Anonymous | Secret of Universe
104 | Anton B   | The Sentinel


table author:
AuthorID|AuthorFullName   |Nationality
=====================================
A01 | Anton Balwin    | USA
J02 | Johannes J Abram| UK


table bookauthor:
BookCode|AuthorID
=================
101 | A01
102 | J02
103 | X01
104 | A01

我有三张表,结构看起来像这样。我希望得到一个查询,结果将是:

如果我这样做查询

select * 
from book tb , author ta, bookauthor tba 
where tb.BookCode = tba.BookCode and tba.AuthorID = ta.AuthorID

由于作者不在表格作者中,因此不会显示row 103 | Anonymous | Secret of Universe

我想要的是:

BookCode| Title         | AuthorID | AuthorShortN
===========================================================
101     | THe Book of Leaves|A01       | Anton Balwin    
102     | Wish Upon A Star  |J02       | Johannes J Abram
103     | Secret of Universe|NULL      | Anonymous
104     | The Sentinel  |A01       | Anton Balwin

如何修复查询以产生这样的结果?

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

Left Join将从左表中提供所有结果,无论右表中是否有相应的条目

SELECT *
FROM book tb
LEFT JOIN author ta ON tb.BookCode = ta.AuthorID
LEFT JOIN bookauthor tba ON ta.AuthorID = tba.BookCode;

另外,关于问题的主题 - 作者表中的作者肖像字段不应该在作者表中吗?

答案 1 :(得分:0)

您正在寻找允许空值的表格上的左连接:

SELECT tb.BookCode, tb.Title, ta.AuthorID, tb.AuthorShortN 
FROM book AS tb
INNER JOIN bookauthor AS tba ON tba.BookCode=tb.BookCode
LEFT JOIN author AS ta ON tba.AuthorID=ta.AuthorID

请注意,您的示例正确输出在AuthorShortN中查找null,并且您实际上在数据中有Anonymous。 BookAuthor的内部联接假设此表中有条目,即使作者是未知的,因为它在您的数据中查找。