多个连接&倍增

时间:2014-01-31 20:50:45

标签: mysql sql

我之前问了一个关于加入的问题,现在我又被卡住了。

这是db的样子:

Book_code (unique)
Price 
book_title
publisher_code
book_type

Branch_num (unique)
Branch_name (unique)
branch_location
num_employees

广告

Branch_number
Book_code
On_hand ( the quantity of books ) 

现在的问题是:列出总库存量(即on_hand次价格之和)大于300的分支。

我知道我必须使用所有表格。我已开始编写以下代码:

SELECT br.branch_name, br.branch_num, i.on_hand , b.book_code, b.price
FROM book b, inventory i, branch br
WHERE br.branch_num = i.branch_num
and b.book_code = i.book_code;

但在此之后我就陷入了困境。

2 个答案:

答案 0 :(得分:0)

SELECT br.branch_name, br.branch_num, SUM(i.on_hand * b.price) as on_hand_price
FROM book b, inventory i, branch br
WHERE br.branch_num = i.branch_num
and b.book_code = i.book_code
GROUP by br.branch_num,br.branch_name
Having Sum(i.on_hand* b.price) > 300
ORDER BY branch_name;

您错过了GROUP分支编号和名称..最后使用SUM验证该组中的hAVING手头金额检查。

答案 1 :(得分:0)

    SELECT a.Branch_Name, a.Branch_Num, sum(i.on_hand * a.price) as TotalInventory
    from Book a
    inner join inventory i
    USING (Book_code)
    inner join Branch b
    ON b.Book_num = i.Book_Num
    group by 1,2 
    HAVING SUM(i.On_hand * a.price) > 300
    order by 3 desc;