使用子查询,可以在哪个分支找到“SQL指南”?列出分支名称,分支位置和可用副本数。不要明确测试书籍代码669X。让MySQL为您完成工作。在此处插入您的查询和结果:
下面的底部代码是否正确?我对如何在子查询中输入它感到困惑,这似乎更简单
使用Henry_Books;
select branch_name,branch_location,inventory.on_hand
from branch,inventory,book
where branch.branch_num = inventory.branch_num
and title = "A guide to SQl" ;
答案 0 :(得分:1)
不需要子查询:
select branch_name,branch_location,
COUNT(inventory.book_id) NumberOfCopies
from branch
inner join inventory on branch.branch_num = inventory.branch_num
inner join book on inventory.book_id = book.book_id
where book.title = "A guide to SQl"
GROUP BY branch_name, branch_location;
(我不知道两个表book
和inventory
之间的关系是什么,所以我猜它将基于book_id
)
如果需要使用子查询,那么你可以这样做,这更复杂,根本不需要它:
select branch_name,branch_location,
( SELECT COUNT(inventory.book_id)
FROM inventory on
inner join book on inventory.book_id = book.book_id
WHERE branch.branch_num = inventory.branch_num
AND book.title = 'A guide to SQl'
) AS NumberOfCopies
from branch
请注意,这是一个相关的子查询。
答案 1 :(得分:0)
简单使用表之间的连接和分组
在你的情况下:
SELECT branch_name,branch_location,inventory.on_hand
FROM branch AS branch
LEFT JOIN inventory AS inventory ON (branch.branch_num = inventory.branch_num )
LEFT JOIN book AS book ON (branch.branch_num = book.branch_num )
WHERE branch.branch_name = "A guide to SQl"
ORDER BY branch.branch_name
GROUP BY branch.branch_name
如果您想使用不推荐的Sub Query
SELECT branch_name,branch_location,on_hand AS (SELECT on_hand FROM inventory WHERE branch.branch_num = inventory.branch_num )
FROM branch AS branch
LEFT JOIN book AS book ON (branch.branch_num = book.branch_num )
WHERE branch.branch_name = "A guide to SQl"
ORDER BY branch.branch_name
GROUP BY branch.branch_name