2017-09-23 39 views
0

使用子查詢,可以在哪個分支上找到「SQL指南」一書?列出分支名稱,分支位置和可用份數。不要明確測試書本代碼669X。讓MySQL爲你做好工作。在此處插入您的查詢和結果:在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" ; 

回答

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_id基地兩個表bookinventory之間的關係)


如果需要使用子查詢來做到這一點,那麼你可以做到這一點,這是更復雜,根本不需要它:

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 

請注意,這是一個相關的子查詢。

+0

我試圖通過子查詢而不是常規方式回答它 – Link45

+0

@ Link45 - 無需子查詢而不需要子查詢,您可以加入,它會給你你想要的。我將用子查詢更新我的答案, – 2017-09-23 07:44:49

+0

好的,謝謝。我想比較這與子查詢看起來像什麼 – Link45

0

簡單使用加入表之間,和你的情況分組

enter image description here

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 

如果你喜歡去與不推薦使用子查詢

enter image description here

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 
+0

列出與客戶編號282 – Link45

+0

@ Link45具有相同代表編號的客戶編號,客戶姓名和銷售代表,這將是您需要詢問的不同問題和不同的線索,因爲您的問題已得到解答,您需要以標記您的問題的最佳答案 – Jack