[英]Limit number of records in MySQL table by checking criteria in other tables
I am creating a very simple database system for book rentals. 我正在为图书租赁创建一个非常简单的数据库系统。 I have a basic MySQL database and a PHP front-end.
我有一个基本的MySQL数据库和一个PHP前端。 I'm familiar with html/css/php/js/ajax, but there is one particular piece of functionality that I can't get right.
我熟悉html / css / php / js / ajax,但是其中一项功能是我无法正确实现的。
So I have a books table and a loans table. 所以我有一个桌子和一个贷款表。 Each book has a "quantity" attribute, and each loan has a "book name (foreign key)", "issue date", and "return date" attribute.
每本书都具有“数量”属性,每笔借书都具有“书名(外键)”,“发行日期”和“归还日期”属性。
I'd like to prevent new loans being created for books where every copy is already on loan. 我想防止为每本已经借出的书都创建新借出。
I'm not sure the best way to go about this - is it common practise to put some logic in the database itself, and monitor the number of copies on loan with an extra table or field? 我不确定执行此操作的最佳方法-在数据库本身中放置一些逻辑并使用额外的表或字段监视借出的副本数是否是常见的做法? Or is it better to handle this kind of logic in the front-end?
还是在前端处理这种逻辑更好?
Thanks in advance. 提前致谢。
There are several possibilities to handle this. 有几种解决方法。 Doing it on DB level is a good practice to make sure the data is always correct.
在数据库级别执行此操作是确保数据始终正确的一种好习惯。
One option is a stored procedure that is used for laoning a book. 一种选择是用于对书进行排版的存储过程。 It would check the tables and insert only if books are available.
它将检查表并仅在有书的情况下插入。 The downside is that if you don't use the procedure you have no garanties that the data is correct.
缺点是,如果不使用该过程,则无法保证数据正确无误。
Another option would be a trigger that throws an error if one tries to insert into the loan table without any books available. 另一种选择是如果一个人尝试在没有可用书籍的情况下插入贷款表,则引发错误。 To throw an error and prevent an insert you can use this line of code in your trigger:
要引发错误并防止插入,可以在触发器中使用以下代码行:
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'insert not allowed because bla bla';
Another option would be using a table that holds a record for every book available and you just set the isAvailable flag in there or dates indicating if it is available or not. 另一个选择是使用一个表,该表为每本可用的书保存一个记录,您只需在其中设置isAvailable标志或日期(指示该书是否可用)即可。 The structure could be like this
结构可能是这样的
books table
-----------
id
title
author
...
book_copies table
-----------------
book_id
book_copy_number
loans table
-----------
id
book_copy_id
loan_date
return_date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.