MySQL - 用于在datetime中更改时间的函数

时间:2016-03-02 08:12:27

标签: mysql datetime

我有一个permission_to列,其日期时间类型为2016-12-31 00:00:00,我想将此值更改为:2016-12-31 23:59:59。我不需要更新行,因为我需要原始值,但我想在查询中使用修改后的值来与另一列进行比较,如下所示:

SELECT
  d.id_machine
  IF(
    d.permission_from < '2016-01-01 00:00:00',
    '2016-01-01 00:00:00',
    d.permission_from
  ) AS date_from,

  IF(
    '(HERE I NEED FUNCTION TO CHANGE DATETIME FROM 2016-12-31 00:00:00 TO 2016-12-31 23:59:59) > 2016-02-02 23:59:59',
    '2016-02-02',
    (AGAIN THE SAME FUCTION)
  ) AS date_to
FROM tbl_decision AS d

是否有任何MySQL函数可以在没有更新的情况下修改日期时间?

4 个答案:

答案 0 :(得分:2)

当我们处理结束日期时,我们通常会在第二天使用,然后我们会使用&#39;小于&#39;与此日期进行比较的操作。

示例:代替2016-12-31,我们正在使用2017-01-01 当我们使用&lt;所以我们把2016年带到最后一刻。

SELECT
  d.id_machine
  IF(
    d.permission_from < '2016-01-01 00:00:00',
    '2016-01-01 00:00:00',
    d.permission_from
  ) AS date_from,

  IF(
    DATE_ADD(d.permission_to,INTERVAL 1 DAY) > 2016-02-02 23:59:59',
    '2016-02-02',
    DATE_ADD(d.permission_to,INTERVAL 1 DAY)
  ) AS date_to
FROM tbl_decision AS d

答案 1 :(得分:1)

您可以使用ADDTIME

 SELECT permission_to,
        ADDTIME(permission_to, '23:59:59') AS new_permission_to
 FROM tbl_decision;

SqlFiddleDemo

输出:

╔══════════════════════════╦═════════════════════════╗
║      permission_to       ║    new_permission_to    ║
╠══════════════════════════╬═════════════════════════╣
║ March, 02 2016 00:00:00  ║ March, 02 2016 23:59:59 ║
╚══════════════════════════╩═════════════════════════╝

答案 2 :(得分:1)

您可以在DATE_ADD函数中使用HOUR_MINUTE格式。

DATE_ADD(permission_to, INTERVAL '23:59' HOUR_MINUTE)

答案 3 :(得分:1)

如果permission_to的类型为datetime,但始终保留2016-12-31 00:00:00之类的值,我会将其存储为日期列而不是日期时间。

无论如何,我会把你的查询写成:

SELECT
  d.id_machine,
  greatest(d.permission_from, '2016-01-01') AS date_from,
  least(d.permission_to + INTERVAL 1 DAY, '2016-02-02') AS date_to
FROM
  tbl_decision AS d

如果您希望获得一天的所有记录,而不是这样,那么这会改变您的逻辑点数:

where
  datetimecolumn>='2016-01-01 00:00:00'
  and datetimecolumn<='2016-01-01 23:59:59'

(如果datetime是2016-01-01 23:59:59.001会怎么样?MySQL现在支持微秒!)只需使用它:

where
  datetimecolumn>='2016-01-01 00:00:00'
  and datetimecolumn<'2016-01-02 00:00:00'