我正在尝试让我的程序显示数据库中所有书架的概述以及相关的书架/隔间以及这些架子或隔间中的书。
我正在使用Microsoft Visual Studio 2017 Windows窗体应用程序。
我的SQL Server数据库结构如下:
user
表(用户名,用户名,密码)bookcase
表(书柜ID,名称,位置,用户ID)Shelf
表(shelfId,bookcaseId)compartment
表(compartmentId,bookcaseId)book
表(书号,标题,作者,意向,类型,隔间ID,架子ID)我知道如何通过使用每个表中的Select *
使用查询来获取所有书籍,书架,用户等的概述。
我也知道要订购,我只需使用Order by bookcaseId
。
我将如何实现?
答案 0 :(得分:1)
您可以使用正确的键将它们加入。
然后从中获取所需的字段。
那个bookcaseId是两个表中的外键。
因此,books表中可能填充了spacerId或/和shelfId。
但是您可以同时加入两者,然后同时获得两者的用户。
SELECT
book.title AS book_title,
book.author AS book_author,
book.serie AS book_serie,
book.genre AS book_genre,
bcs.name AS shelf_bookcase_name,
bcs.location AS shelf_bookcase_location,
us.username AS shelf_bc_username,
bcc.name AS compartment_bookcase_name,
bcc.location AS compartment_bookcase_location,
uc.username AS compartment_bc_username
FROM book
LEFT JOIN compartment AS cmp ON cmp.compartmentId = book.compartmentId
LEFT JOIN bookcase AS bcc ON bcc.bookcaseId = cmp.bookcaseId
LEFT JOIN [user] AS uc ON uc.userId = bcc.userId
LEFT JOIN shelf ON shelf.shelfId = book.shelfId
LEFT JOIN bookcase AS bcs ON bcs.bookcaseId = shelf.bookcaseId
LEFT JOIN [user] AS us ON us.userId = bcs.userId
ORDER BY coalesce(shelf.bookcaseId, cmp.bookcaseId)
答案 1 :(得分:1)
另一种可能的方法是对bookshelves
子句使用FROM
。之所以采用这种方法(如果我正确理解了您的数据库设计),是因为bookcaseId
似乎是shelf
和compartment
表中的外键。
SELECT
bk.bookcaseId, bk.name, bk.location,
b.bookid, b.title, b.author, b.serie, b.genre, b.compartmentId, b.shelfId
FROM bookcase bk
LEFT JOIN shelf s ON (bk.bookcaseId = s.bookcaseId)
LEFT JOIN compartment c ON (bk.bookcaseId = c.bookcaseId)
LEFT JOIN book b ON (c.compartmentId = b.compartmentId) AND (s.shelfId = b.shelfId)
ORDER BY bk.bookcaseId, s.shelfId, c.compartmentId