【问题标题】:Separate Date and Time from a DateTime column and put each into it's own Date and Time column从 DateTime 列中分离日期和时间并将每个放入它自己的日期和时间列
【发布时间】:2015-11-07 23:05:16
【问题描述】:

我在 MySQL 数据库中有一个“日期时间”列 (Y-m-d H:i:s)。要执行我想要执行的查询,我需要将日期和时间分开并将每个放入它自己的列中。我曾尝试在 MySQL 中使用“更新”来执行此操作,并创建了一个新的“日期”和“时间”列来放入数据。我尝试的一切都将数据作为全零放入列中。如何将这些数据分成各自的列?

编辑:现在的查询是查看我在特定日期有哪些约会。在我进行查询时使用 datetime 列,假设 2015-08-19 @ 1:00 PM 它只带回该确切日期和时间的约会。我希望查询能够恢复某个日期的所有约会,无论时间如何。

这是我的 SELECT 语句

$appt_date = date('Y-m-d H:i:s', strtotime($appt_date));

    $query = $mysqli->prepare("
SELECT set_date
     , branch
     , appt_date
     , employee
     , fname
     , lname
     , last_four
     , phone
     , city
     , state
     , zip 
  FROM appointments 
 WHERE set_date BETWEEN '".$from."' AND '".$to."' 
   AND set_date LIKE CONCAT('%', ?, '%') 
   AND branch LIKE CONCAT('%', ?, '%') 
   AND appt_date = (?) 
   AND employee LIKE CONCAT('%', ?, '%') 
   AND fname LIKE CONCAT('%', ?, '%') 
   AND lname LIKE CONCAT('%', ?, '%') 
   AND last_four LIKE CONCAT('%', ?, '%') 
   AND phone LIKE CONCAT('%', ?, '%') 
   AND city LIKE CONCAT('%', ?, '%') 
   AND state LIKE CONCAT('%', ?, '%') 
   AND zip LIKE CONCAT('%', ?, '%') 
 ORDER 
    BY set_date ASC
");

【问题讨论】:

  • 不是为了回避这个问题,但是在需要将日期时间分成实际表中的两个单独列的情况下,您可能想要执行什么查询?
  • 为什么要两个字段?如果你想要日期或时间组件,你可以简单地做select time(datetimefield), date(datetimefield) 将它们分开只会在以后导致痛苦,例如timefield=timefield + interval 23 hour,哎呀,不,你搞砸了你的约会,因为你没有做datefield=datefield+interval 1 day来解释时间字段的变化。
  • @MarcB:你能索引标量函数调用吗?
  • mysql 的内部日期/时间表单很容易扫描这类事情,整个字段上只有一个索引。
  • @TabAlleman:不考虑时间查询日期是很常见的。如果想查看某一天发生的所有事情并且我必须涉及时间,我将不得不使用between(或 Marc 建议的<' and '>') in order to account for the span of time that accounts for that day. If you can query on a date only (either by using a dedicated field or something like date()`),您可以使用简单的相等检查.

标签: mysql sql date datetime time


【解决方案1】:
SELECT '2015-08-19 01:00:00' BETWEEN '2015-08-19' AND '2015-08-20' x;
+---+
| x |
+---+
| 1 |
+---+

SELECT '2015-08-20 01:00:00' BETWEEN '2015-08-19' AND '2015-08-20' x;
+---+
| x |
+---+
| 0 |
+---+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多