php - 插入当前时间时如何计算上次时间和总时间?

标签 php mysql datetime

我正在尝试将当前项目持续时间和项目名称存储在一个表中。其中还包括当前持续时间、先前持续时间和总持续时间。

我在表单中输入项目名称和当前持续时间并存储到表格中,但是当我添加更多项目时,如何计算之前的持续时间和总持续时间?

projects_id - int (auto increment)
project - varchar
current_time - int
previous_time - int
total_time - int

首先我将previous_timetotal_time初始化为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)

关于php - 插入当前时间时如何计算上次时间和总时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22215916/

相关文章:

php - PHP、PDO(可能不是 MySQL)的神秘之处 SQLSTATE[42000](1064)

Python/MySQL "Insert into"带变量

javascript - 通过 $.post 动态加载内容不保留点击事件

c# - 如何获取不同时区的当前 UTC 偏移量?

php - 页面刷新后记住选择的选项

php - 拉维尔;如何使 setLocale 永久化?

sql - 我如何将条件按时间段分组?

javascript - 如何在 JavaScript 中将字符串格式的 UTC 日期无偏移地转换为本地时间?

php - CodeIgniter get_where order_by

PHP PDO 使用下拉菜单过滤数据