从5个表格中获取数据

时间:2018-08-07 19:06:13

标签: sql vb.net

我有5个表格:tblbooktblauthortblpublishertblauthorbooktblbookpublisher

  • tblbook具有以下列:
    • BookID
    • Barcode
    • ISBN
    • BookSection
    • BookCopyNumber
  • tblauthor

    • AuthorID
    • AuthorName
  • tblpublisher

    • publisherID
    • publishername
  • tblauthorbook

    • AuthorID
    • BookID
  • tblbookpublisher
    • publisherID
    • BookID

我需要做的是在列表视图中显示与vbnet中输入的条形码编号相等的所有书籍,以及它们的authornamepublisher

我对如何执行此操作感到困惑,这是我尝试过的查询:

"Select tblbook.BookID, 
   tblbook.BookTitle,
   tblbook.BookSection,
   tblauthorbook.AuthorID,
   tblauthorbook.BookID,
   tblauthor.AuthorID,
   tblauthor.AuthorName,
   tblbookpublisher.PublisherID,
   tblbookpublisher.BookID,
   tblpublisher.PublisherID,
   tblbook.AcSecCode 
 from tblbook, 
   tblauthorbook, 
   tblauthor, 
   tblbookpublisher, 
   tblpublisher 
 where tblbook.Barcode = '" & txtbarcode.Text & "' 
   and tblbook.BookID = tblauthorbook.BookID 
   and tblauthorbook.AuthorID = tblauthor.AuthorID 
   and tblbook.BookID = tblbookpublisher.BookID 
   and tblbookpublisher.PublisherID = tblpublisher.PublisherID"

没有错误,但它在列表视图中未显示任何内容,因此我的查询一定是错误的。有人可以帮助我如何正确查询吗?预先谢谢你

1 个答案:

答案 0 :(得分:0)

手动尝试此查询,并检查其是否返回内容。

外键之一可能为空。
通过使用LEFT JOIN,可以很容易地在结果中注意到这一点。

select 
 b.BookID, b.BookTitle, b.BookSection,
 ab.AuthorID, ab.BookID,
 a.AuthorID, a.AuthorName,
 bp.PublisherID, bp.BookID,
 p.PublisherID,
 b.AcSecCode
from tblbook b
left join tblauthorbook ab on ab.BookID = b.BookID 
left join tblauthor a on a.AuthorID = ab.AuthorID 
left join tblbookpublisher bp on bp.BookID = b.BookID 
left join tblpublisher p on p.PublisherID = bp.PublisherID
where b.Barcode = @YourBarCode

但是首先替换或声明并设置@YourBarCode变量