mySQL找到可用的书并借用它

时间:2017-02-01 23:57:46

标签: mysql sql database

我创建了一个图书馆系统,我试图设置一个程序,允许您输入一个isbn和学生编号,并从中检查数据库以查看该书是否可用,如果是,书籍它。如果没有,则给出错误消息。

我的表格如下:

  • book - pk_isbn,作者,标题
  • copy - pk_code,duration,fk_isbn
  • loan - fk_code,fk_no,pk_taken,due,return_date
  • 学生 - pk_no,姓名,学校,allowedtobook

这是我目前的代码明智*有些只是一种伪代码,我想它目前还没有完成。

DELIMITER $$
CREATE PROCEDURE issue_loan (IN book_isbn CHAR(17), IN stu_no INT)

BEGIN

DECLARE availablebooks INT;
DECLARE allowedtobook BIT;

SET availablebooks = (SELECT DISTINCT
        c.isbn
    FROM
        loan l
            INNER JOIN
        student s ON l.no = s.no
            INNER JOIN
        copy c ON l.code = c.code
    WHERE
        return_date IS NOT NULL);

IF(availablebooks = book_isbn) AND s.embargo = 0 THEN
INSERT INTO loan VALUES
(code, stu_no, CURDATE(), CURDATE()+c.duration,'');
ELSE 
SIGNAL SQLSTATE '450000' SET MESSAGE_TEXT ='no Books Available';
END IF;

END$$

return_date IS NOT NULL的部分应该是正确的,因为它找到了尚未归还的任何书籍。这意味着他们目前正在预订。

1 个答案:

答案 0 :(得分:0)

您无法将变量设置为查询结果集,变量只能包含一个值。您只需将book_isbns.embargo = 0的比较添加到查询中即可。

SET @book_available = (SELECT COUNT(*)
    FROM loan l
    INNER JOIN student s ON l.no = s.no
    INNER JOIN copy c ON l.code = c.code
    WHERE c.fk_isbn = book_isbn AND s.embargo = 0 AND l.return_date IS NULL);

IF @book_available
THEN 
    INSERT INTO loan (fk_code, fk_no, pk_taken, due, return_date)
    VALUES (code, stu_no, CURDATE(), CURDATE()+c.duration,'');
ELSE SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT ='no Books Available';
END IF