我在MySQL上的第一个ADD / Subtract

时间:2013-03-24 23:57:27

标签: mysql

给出一个如下表:

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

如何添加前三列并将总数显示在Total Books列中?

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

2 个答案:

答案 0 :(得分:1)

你的意思是更新'总书籍'根据你在下面提供的计算? 试试这个:

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

您也可以使用triggers

' PHP和MySQL for dummies'在我看来是一本好书。但是Lynda.com的一些网络教程也很有帮助!

答案 1 :(得分: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 |
+-----------------+---------------+----------------+-------------+