我从以下流程图创建了一个数据库:
根据这个填充:
- 有一本名为“The Lost Tribe”的书。
- 有一个名为'Sharpstown'的图书馆分支和一个名为'Central'的图书馆分支。
- BOOK表中至少有20本书。
- BOOK_AUTHORS表中至少有10位作者。
- 每个图书馆分馆至少有10本书名,每本书至少有两份。
- BORROWER表中至少有8位借款人,其中至少有2位借款人拥有超过5本借给他们的书。
- LIBRARY_BRANCH表格中至少有4个分支。
- BOOK_LOANS表中至少有50笔贷款。
- 必须至少有一本书由'Stephen King'撰写
醇>
我试图找到名为 The Lost Tribe 的书的副本有多少是由图书馆分支所有。 是“ Sharpstown ”。现在我知道通过找出 Sharpstown 的BranchId,我可以运行以下查询:
SELECT No_Of_Copies FROM BOOK_COPIES WHERE BookId = 1 and BranchId = 1
但有没有办法使用实际名称“ Sharpstown ”进行搜索?
感谢您的帮助,我是SQL SERVER的新手,并且不知道一个用户可以通过查询获得具体的具体信息。
答案 0 :(得分:0)
当然可以。
如果您想使用correlated subquery
:
SELECT No_Of_Copies FROM BOOK_COPIES
WHERE BranchId IN (
SELECT BranchId FROM LIBRARY_BRANCH WHERE BranchName = "Sharpstown")
AND BookId IN (
SELECT BookId FROM BOOK WHERE Title = "The Lost Tribe" )
或者你可以使用@Sachin在另一个答案中建议的连接。
答案 1 :(得分:0)
对于图书馆分支,您可以使用IN
SELECT No_Of_Copies FROM BOOK_COPIES
WHERE BookId = 1
AND BranchId IN (SELECT BranchId
FROM library_branch
WHERE BranchName = 'Sharpstown');
答案 2 :(得分:0)
您必须使用Join来满足该要求。您必须使用BOOK_COPIES
和LIBRARY_BRANCH
表加入BOOK
,然后您可以BranchName
找到
SELECT No_Of_Copies
FROM BOOK_COPIES inner join LIBRARY_BRANCH
on BOOK_COPIES .BranchId = LIBRARY_BRANCH.BranchId
inner join BOOK
on BOOK_COPIES.BookId = BOOK.BookId
WHERE BOOK.Title = "The Lost Tribe" and LIBRARY_BRANCH.BranchName = "Sharpstown"
答案 3 :(得分:0)
试试这个。
SELECT No_Of_Copies FROM BOOK_COPIES
WHERE BranchId in
(
select BranchId from library_branch
where branchname like '%Sharpstown%'
)
and BookId in
(
select BookId
from book where title like
'%The Lost Tribe%'
)
答案 4 :(得分:0)
SELECT No_Of_Copies FROM BOOK_COPIES
LEFT JOIN LIBRARY_BRANCH on BOOK_COPIES.BranchId=LIBRARY_BRANCH.BranchId
WHERE BookId = 1 and BranchName = 'Sharpstown'
答案 5 :(得分:0)
SELECT No_Of_Copies
FROM BOOK_COPIES
WHERE BookId=(SELECT BookId FROM BOOK WHERE Title="The Lost Tribe")
AND branchid=(SELECT BranchId FROM LIBRARY_BRANCH WHERE BranchName="Sharpstown")
如果您正在寻找完全匹配,请使用Title="The Lost Tribe"
,然后使用Title LIKE "%The Lost Tribe%"
答案 6 :(得分:0)
如果您想动态获取图书ID,可以使用内部联接。
SELECT BC.NOOFCOPIES FROM
BOOK_COPIES BC INNER JOIN BOOK B ON B.BOOKID = BC.BOOKID
INNER JOIN BRANCH BR ON BC.BRANCHID = BR.BRANCHID
WHERE BR.BRANCHNAME = 'SHARPSTOWN';