1
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

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

非常感谢您的帮助。

4

2 回答 2

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;

另外,题外话 - AuthorShortN 字段不应该在作者表中吗?

于 2013-09-04T05:56:56.990 回答
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 的内部联接假定即使作者未知,此表中也有条目,因为它在您的数据中查找。

于 2013-09-04T06:02:20.197 回答