我正在尝试将当前项目持续时间与项目名称存储在一个表中。它还包括当前持续时间,前一个持续时间和总持续时间。
我在表单中输入项目名称和当前持续时间并存储到表中,但是当我添加更多项目时,如何计算之前的持续时间和总持续时间?
projects_id - int (auto increment)
project - varchar
current_time - int
previous_time - int
total_time - int
首先,我会将previous_time
和total_time
初始化为0
然后在插入新行时,我将更新项目名称和当前时间,必须自动计算上一次和总时间。
答案 0 :(得分:0)
您可以考虑的表格结构:
mysql> desc project;
+---------------+-------------+------+-----+---------------------+----------------------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------------------+----------------------------+
| project_id | int(1) | NO | PRI | NULL | auto_increment |
| project | varchar(20) | YES | | NULL | |
| current_t | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP|
| previous_time | timestamp | NO | | 0000-00-00 00:00:00 | |
| total_time | time | YES | | NULL | |
+---------------+-------------+------+-----+---------------------+----------------------------+
5 rows in set (0.01 sec)
示例数据
mysql> select * from project;
+------------+---------+---------------------+---------------------+------------+
| project_id | project | current_t | previous_time | total_time |
+------------+---------+---------------------+---------------------+------------+
| 1 | test | 2014-03-06 12:36:34 | 2014-03-06 10:27:19 | 00:00:00 |
+------------+---------+---------------------+---------------------+------------+
1 row in set (0.00 sec)
执行您要查找的更新的SQL:
REPLACE INTO project (project_id,previous_time,total_time)
SELECT project_id,current_t,total_time + TIMEDIFF(NOW(),current_t)
FROM project
WHERE project_id = 1
更新的表格:
mysql> select * from project;
+------------+---------+---------------------+---------------------+------------+
| project_id | project | current_t | previous_time | total_time |
+------------+---------+---------------------+---------------------+------------+
| 1 | NULL | 2014-03-06 12:41:22 | 2014-03-06 12:36:34 | 00:04:48 |
+------------+---------+---------------------+---------------------+------------+
1 row in set (0.00 sec)