多个SQL连接

时间:2011-05-12 19:00:37

标签: sql sqlite join

我需要执行查询要从多个表中检索数据,但我对如何一次完成所有操作感到困惑。

Books: _ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Categories: _CategoryID, Category
Categories_Books: _Categories_Category_ID, _Books_ISBN
Publishers: _Publisherid, Publisher
Writers: _WriterID, LastName
Writers_Books: _Writers_WriterID, _Books_ISBN

Categories_BooksWriters_Books是帮助我在表之间实现多对多关系的中间表。

我需要一个带有多个连接的查询来选择:

  • 标题,版本,年份,页数,书籍评级
  • 类别中的类别
  • 发布商发布商
  • 作家的姓氏

3 个答案:

答案 0 :(得分:108)

会是这样的:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

您使用join语句指示表A中的哪些字段映射到表B.我在这里使用别名这就是为什么您看到Books b Books表将会是在查询的其余部分中称为b。这样可以减少打字。

FYI你的命名惯例很奇怪,我希望它更像是这样:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

答案 1 :(得分:26)

您可以使用以下内容:

SELECT
    Books.BookTitle,
    Books.Edition,
    Books.Year,
    Books.Pages,
    Books.Rating,
    Categories.Category,
    Publishers.Publisher,
    Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.

答案 2 :(得分:3)

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID