1

Given a table that looks like this:

| Book in Shelves | Arrived Books | Borrowed Books | Total Books |
        15               10                5              ?

How can I add the first three columns and have the total appear in the Total Books column?

Book in Shelves + Arrived books - Borrowed Books = Total Books
4

2 回答 2

1

在设计数据库时,您不存储可以从其他值计算的值。这将使您的数据库不一致。例如:如果您将 更新Book in Shelves为 20,则必须添加另一个查询来编辑Total Books. 所以永远不要添加你可以计算的列。从数据库中检索数据时,您可以执行以下操作:

SELECT `Book in Shelves`, `Arrived Books`, `Borrowed Books`, (`Book in Shelves` + `Arrived Books` - `Borrowed Books`) AS `Total books` FROM `table`;

结果:

+-----------------+---------------+----------------+-------------+
| Book in Shelves | Arrived Books | Borrowed Books | Total books |
+-----------------+---------------+----------------+-------------+
|              15 |            10 |              5 |          20 |
|              44 |            22 |              5 |          61 |
|              12 |             2 |              7 |           7 |
+-----------------+---------------+----------------+-------------+
于 2013-03-25T00:15:16.433 回答
1

您的意思是通过您在下面提供的计算来更新“总图书”?尝试这个:

UPDATE `tablename` SET total_books=(books_in_shelves+arrived_books-borrowed_books)

您也可以使用触发器

'PHP and MySQL for dummy' 在我看来是一本好书。但是,例如 Lynda.com 上的一些互联网教程也很有帮助!

于 2013-03-25T00:10:07.267 回答