Mysql 比较DateTime和Timestamp

Mysql 比较DateTime和Timestamp,mysql,timestamp,Mysql,Timestamp,我创建了一个sql查询,并返回了不可预知的结果,这让我很长时间都感到困扰 SELECT (CURRENT_TIMESTAMP - INTERVAL 90 DAY) AS 'threshold_time', txs.created_at, (CASE WHEN txs.created_at >= 'threshold_time' THEN 1 ELSE 0 END) AS 'chosen' FROM transactions txs 结果是: threshold_time |

我创建了一个sql查询,并返回了不可预知的结果,这让我很长时间都感到困扰

SELECT 
(CURRENT_TIMESTAMP - INTERVAL 90 DAY) AS 'threshold_time', 
txs.created_at, 
(CASE WHEN txs.created_at >= 'threshold_time' THEN 1 ELSE 0 END) AS 'chosen'
FROM transactions txs
结果是:

threshold_time     |created_at         |chosen|
-------------------|-------------------|------|
2019-08-15 23:33:40|2019-10-23 05:36:22|     0|
2019-08-15 23:33:40|2019-10-24 06:02:43|     0|
2019-08-15 23:33:40|2019-11-11 01:43:36|     0|
threshold_time     |created_at         |chosen|
-------------------|-------------------|------|
2019-08-15 23:51:43|2019-10-23 05:36:22|     1|
2019-08-15 23:51:43|2019-10-24 06:02:43|     1|
2019-08-15 23:51:43|2019-11-11 01:43:36|     1|
奇怪的是,所有选择的值都应该是1,但都是0。 如果我换成

SELECT 
(CURRENT_TIMESTAMP - INTERVAL 90 DAY) AS 'threshold_time', 
txs.created_at, 
(CASE WHEN (txs.created_at - 'threshold_time') >= 0 THEN 1 ELSE 0 END) AS 'chosen'
FROM transactions txs
结果是:

threshold_time     |created_at         |chosen|
-------------------|-------------------|------|
2019-08-15 23:33:40|2019-10-23 05:36:22|     0|
2019-08-15 23:33:40|2019-10-24 06:02:43|     0|
2019-08-15 23:33:40|2019-11-11 01:43:36|     0|
threshold_time     |created_at         |chosen|
-------------------|-------------------|------|
2019-08-15 23:51:43|2019-10-23 05:36:22|     1|
2019-08-15 23:51:43|2019-10-24 06:02:43|     1|
2019-08-15 23:51:43|2019-11-11 01:43:36|     1|

有人能解释一下吗?

下面的
案例
表达式将在
列中创建的
与字符串
'threshold\u time'
进行比较:

CASE WHEN txs.created_at >= 'threshold_time' THEN 1 ELSE 0 END
以下是更正后的工作版本:

SELECT 
    CURRENT_TIMESTAMP - INTERVAL 90 DAY AS threshold_time, 
    txs.created_at, 
    (CASE WHEN txs.created_at >= CURRENT_TIMESTAMP - INTERVAL 90 DAY
          THEN 1 ELSE 0 END) AS chosen
FROM transactions txs;
但实际上在MySQL中,布尔表达式的默认值为0或1,因此可以将上述内容简化为:

SELECT 
    CURRENT_TIMESTAMP - INTERVAL 90 DAY AS threshold_time, 
    txs.created_at, 
    txs.created_at >= CURRENT_TIMESTAMP - INTERVAL 90 DAY AS chosen
FROM transactions txs;

第二种情况是比较时间戳和字符串,但为什么结果大于0?这与正在发生的隐式转换有关。字符串不能直接与日期进行比较,因此MySQL将一个字符串转换为另一个字符串。这里重要的是理解语法错误。