【问题标题】:Issue In Mysql Date Comparison [duplicate]Mysql日期比较中的问题[重复]
【发布时间】:2021-03-24 22:13:58
【问题描述】:

我有一个表,其中有一个 datetime 列,如下所示:

 ---------------------
|   date_time_column  |
 ---------------------
| 2020-09-14 14:00:13 |
| 2020-05-18 14:00:13 |
| 2021-12-14 14:00:13 |
 ---------------------

当我进行这些查询时

select * from `table` 
        where TIMESTAMP('date_time_column') < '2020-12-14 10:20:04' 

但结果是什么都没有

【问题讨论】:

  • 这只是因为您的客户端没有显示值的完整分辨率(一些毫秒部分)。因此,它们都不完全等于您请求的时间。尝试在 10:20:04 到 10:20:05 之间获取。
  • 您希望从此查询返回什么?
  • 如果在 where 条件下使用完整的 datetime 则无需使用 TIMESTAMP,只需使用此 select * from table where date_time_column
  • 'date_time_column' 是一个字符串。也许你在想`date_time_column`
  • 您是否尝试过调试您的查询? select *, timestamp('date_time_column') from table 产生了什么?另外,你能分享一下你的表的架构吗?

标签: mysql sql string datetime where-clause


【解决方案1】:

您正在将 文字字符串 'date_time_column' 转换为时间戳,而不是实际的列。由于这个字符串显然不是一个有效的时间戳,你会得到一个null 结果,它会过滤掉所有的行。

select timestamp('date_time_column') as res
|资源 | | :--- | | |

你想要反引号而不是单引号,例如:

select * 
from `table` 
where timestamp(`date_time_column`) < '2020-12-14 10:20:04' 

不引用标识符也足够好:

where timestamp(date_time_column) < '2020-12-14 10:20:04' 

归根结底,时间戳转换没有任何好处,并且会减慢查询速度。直接过滤即可:

where date_time_column < '2020-12-14 10:20:04' 

【讨论】:

  • 问题是我之前做过这些查询并且没有返回原始数据,当它在本地工作但在服务器上不起作用时
  • @AbdullahAl_Nahhal:我不知道你在说什么。答案解释了问题(单引号而不是反引号),并解释了如何解决它。您是否尝试过建议的解决方案?
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多