我正在学习我的第一个编程(sql)课程。我没有任何技术背景,我在解决代码方面遇到了一些麻烦。 这是数据库的样子。
BOOK_CODE (UNIQUE)
BOOKTITLE
PUBLISHER_CODE
BOOKTYPE
PRICE
BOOK_CODE (UNIQUE)
BRANCH_NUM (UNIQUE)
ON_HAND
问题是,列出分支3和4中可用的书籍(标题)(同时在两者上)。
我想我需要使用下面的表:书桌上的booktitle,两个表上的bookcode(书和库存),以及库存表上的branch_num。
答案也只能显示第3和第4分支(同时)可用的书名,而不能显示其他列。
抱歉,如果我没有意义。就像我说我是一个n00b。答案 0 :(得分:2)
select distinct BOOKTITLE from BOOK a, INVENTORY b
where a.BOOK_CODE = b.BOOK_CODE and a.BOOK_CODE in
(select distinct p.BOOK_CODE from Inventory p, Inventory q where p.BOOK_CODE =
q.BOOK_CODE
and p.BRANCH_NUM = 3 AND q.BRANCH_NUM = 4);
答案 1 :(得分:1)
SELECT BOOKTITLE FROM BOOK
WHERE BOOK_CODE IN (SELECT BOOK_CODE FROM INVENTORY WHERE BRANCH_NUM = 3 AND ON_HAND > 0)
AND BOOK_CODE IN (SELECT BOOK_CODE FROM INVENTORY WHERE BRANCH_NUM = 4 AND ON_HAND > 0);
OR
SELECT BOOKTITLE FROM
(
SELECT BOOK.BOOK_CODE, BOOKTITLE, COUNT(*) AS BRANCH_COUNT FROM BOOK
INNER JOIN INVENTORY ON BOOK.BOOK_CODE = INVENTORY.BOOK_CODE
AND INVENTORY.BRANCH_NUM IN (3, 4)
GROUP BY BOOK.BOOK_CODE, BOOKTITLE
) B
WHERE B.BRANCH_COUNT = 2;
答案 2 :(得分:1)
请试试这个:
SELECT BK.BOOKTITLE
FROM BOOK BK
INNER JOIN INVENTORY INV1
ON INV1.BOOK_CODE = BK.BOOK_CODE
INNER JOIN INVENTORY INV2
ON INV2.BOOK_CODE = BK.BOOK_CODE
WHERE INV1.BRANCH_NUM = 3
AND INV2.BRANCH_NUM = 4
答案 3 :(得分:1)
您的问题会告诉您表格中所需的字段,以此为出发点:
SELECT booktitle FROM book . . .
仅此一项就会为您提供表booktitle
中每个book
的列表,但您希望将其过滤为branch_num
3和4中的所有书籍。
当您JOIN
两个或更多表时,您希望根据某些共享值匹配行; book_code
,在这种情况下。
由于您只想在两个表格中看到这些图书,因此您需要使用INNER JOIN
。 (我假设ON_HAND是一个描述分支中副本数量的INT。)
SELECT booktitle FROM book
INNER JOIN inventory USING (book_code)
WHERE inventory.onhand > 0
该查询将返回任何分支中可用的每本书的列表。修改查询,您只能将其限制为branch_num
3:
SELECT booktitle FROM book
INNER JOIN inventory USING (book_code)
WHERE inventory.onhand > 0 AND inventory.branch_num = 3
...但是您需要分支3和4中的书籍,因此您需要在inventory
表格上进行另一次加入。但你怎么能区分这两者呢?使用表别名:
SELECT booktitle FROM book
INNER JOIN inventory AS inventory1 USING (book_code)
INNER JOIN inventory AS inventory2 USING (book_code)
WHERE inventory1.onhand > 0 AND inventory1.branch_num = 3 AND inventory2.onhand > 0 AND inventory2.branch_num = 4
这应该可以为您提供所需的信息。
要更好地解释联接,请参阅MySQL Joins和A Visual Explanation of SQL Joins。
[注意:这个问题也可能是你应该尝试使用的子查询。]