dongmei8511 2017-12-31 11:35
浏览 39
已采纳

如何从sql中的特定日期获取数据

I am trying to get the data of the current date in MySQL. I have a column named created_at which stores the date and time (2017-12-31 11:32:54)using the NOW() function using the statements,

    $stmt = $this->conn->prepare("INSERT INTO log(id, name, created_at) VALUES(?, ?, NOW())");
    $stmt->bind_param("ss", $id, $name);
    $result = $stmt->execute();

Now I want to ignore the time in the created_at column and retrieve the data of the current date (today's date).

I tried using this query,

SELECT * FROM log WHERE created_at = DATE_SUB(CURDATE(), INTERVAL 0 DAY)

But this results in zero rows selected.

Please help me solve this issue.

  • 写回答

2条回答 默认 最新

  • dongyi2993 2017-12-31 11:38
    关注

    One option would be to wrap created_at with DATE(), and then compare to CURDATE():

    SELECT *
    FROM log
    WHERE DATE(created_at) = CURDATE();
    

    But this has the drawback of precluding the possibility of using an index on the created_at column. We could also phrase this as follows:

    SELECT *
    FROM log
    WHERE created_at >= CURDATE() AND created_at < CURDATE() + INTERVAL 1 DAY;
    

    This would allow an index to be used on created_at, though it is a bit more verbose.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端