找到可用的份数

时间:2014-04-23 00:11:10

标签: mysql sql

我试图在用户输入的书名中找到每个分支的可用书籍副本数量。到目前为止,我试过这个:

   select (bc.no_of_copies-count(bl.book_id)) as avail 
     from book_copies bc
        , book_loans bl
        , book b
        , book_authors ba 
    where bc.book_id=bl.book_id 
      and bc.branch_id=bl.branch_id 
      and ba.book_id=bc.book_id 
      and b.book_id=ba.book_id 
      and b.book_id=bc.book_id 
      and b.title LIKE '%funda%' 
      and bl.date_in IS NULL 
    GROUP BY bc.branch_id;

但它总是返回一个空集。 这是我正在使用的架构:

CREATE TABLE BOOK (
    Book_id varchar(100),
    Title   varchar(100),
    PRIMARY KEY (Book_id)
);

CREATE TABLE BOOK_AUTHORS(
    Book_id     varchar(100),
    Authors varchar(100),
    Fname varchar(100),
    Minit varchar(100),
    Lname varchar(100),
    PRIMARY KEY (Book_id, Authors),
    FOREIGN KEY (Book_id) REFERENCES BOOK(Book_id)
);

CREATE TABLE LIBRARY_BRANCH(
    Branch_id   int(5),
    Branch_name varchar(100),
    Address     varchar(100),
    PRIMARY KEY (Branch_id)
);

CREATE TABLE BOOK_COPIES (
    Book_id     varchar(100),
    Branch_id   int(5),
    No_of_copies int(5),
    PRIMARY KEY (Book_id, Branch_id),
    FOREIGN KEY (Book_id) REFERENCES BOOK(Book_id),
    FOREIGN KEY (Branch_id) REFERENCES LIBRARY_BRANCH(Branch_id)
);

CREATE TABLE BORROWER (
    Card_no varchar(100),
    Fname   varchar(100),
    Lname   varchar(100),
    Address varchar(100),
    Phone   varchar(100),
    PRIMARY KEY (Card_no)
);
CREATE TABLE Book_Loans(
    Loan_id varchar(100),

    Book_id     varchar(100),

    Branch_id   int(5),

    Card_no     varchar(100),

    Date_out    date,

    Due_date    date,

    PRIMARY KEY (Loan_id),

    FOREIGN KEY (Book_id) REFERENCES BOOK(Book_id),

    FOREIGN KEY (Branch_id) REFERENCES LIBRARY_BRANCH(Branch_id),

    FOREIGN KEY (Card_no) REFERENCES BORROWER(Card_no)
);

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为你想要的是:

Select Sum(bc.No_of_copies), bc.Branch_id  from BOOK_COPIES bc
INNER JOIN BOOK bk  ON bk.Book_id = bc.Book_id
WHERE bk.Title LIKE '%funda%'
GROUP BY bc.Branch_id

添加你需要的任何其他参数(你有date_in,但不在你的表中任何地方,我猜你的意思是Due_Date,但这个框架应该让你开始)。

我的想法是,您将无法使用此架构跟踪唯一项目。您有特定标题的数量,但无法区分唯一的项目。你可能应该有一个具有唯一ID的每本书的实例(所以如果你在Rye中有5个Catcher副本,你在黑麦中有5个Catcher的ID,所以你知道副本1被签出给Bob,并且复制2检查了Sally,而不是Bob有一本书,Sally有一本书,因为当一本书在回报中掉线时会发生什么,是Bob或Sally的吗?)