mysql - 我可以将 MysQL 时间戳与日期时间列进行比较吗?不好吗?

标签 mysql datetime timestamp

所以,我有一个表,其中“ABC”列是时间戳,“BCD”列是日期时间。

如果我这样做:

SELECT * FROM myTable WHERE ABC > BCD

不好吗?会影响性能吗?

它们在性能方面的比较如何?

最佳答案

是的,您可以将 datetimetimestamp 进行比较。这还不错,但要注意以下几点:

Remember that although DATETIME, DATE, and TIMESTAMP values all can be specified using the same set of formats, the types do not all have the same range of values. For example, TIMESTAMP values cannot be earlier than 1970 UTC or later than '2038-01-19 03:14:07' UTC.

This means that a date such as '1968-01-01', while legal as a DATETIME or DATE value, is not valid as a TIMESTAMP value and is converted to 0.

来自 MySQL Reference Manual :: The DATETIME, DATE, and TIMESTAMP Types .

请注意以下测试用例如何正常工作:

CREATE TABLE t1 (d1 datetime, d2 timestamp);

INSERT INTO t1 VALUES ('1968-01-01 00:00:00', '1980-01-01 00:00:00');
INSERT INTO t1 VALUES ('2040-01-01 00:00:00', '1980-01-01 00:00:00');

SELECT * FROM t1 WHERE d2 < d1;
+---------------------+---------------------+
| d1                  | d2                  |
+---------------------+---------------------+
| 2040-01-01 00:00:00 | 1980-01-01 00:00:00 |
+---------------------+---------------------+
1 row in set (0.00 sec)

SELECT * FROM t1 WHERE d2 > d1;
+---------------------+---------------------+
| d1                  | d2                  |
+---------------------+---------------------+
| 1968-01-01 00:00:00 | 1980-01-01 00:00:00 |
+---------------------+---------------------+
1 row in set (0.00 sec)

SELECT * FROM t1 WHERE d2 < '2040-01-01 00:00:00';
+---------------------+---------------------+
| d1                  | d2                  |
+---------------------+---------------------+
| 1968-01-01 00:00:00 | 1980-01-01 00:00:00 |
| 2040-01-01 00:00:00 | 1980-01-01 00:00:00 |
+---------------------+---------------------+
2 rows in set (0.00 sec)

SELECT * FROM t1 WHERE d2 > '2040-01-01 00:00:00';
Empty set (0.00 sec)

关于mysql - 我可以将 MysQL 时间戳与日期时间列进行比较吗?不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3886269/

相关文章:

Android比较日期时间

python - pandas 将 2 个具有不同日期索引的数据帧组合在一起

linux-kernel - 从 x86 内核获取 TSC 速率

java - 如何在jboss日志记录的模式格式化程序中自定义时间戳

sql - 如何在不丢失小时、分钟和秒的情况下向 Hive 时间戳添加天数

mysql - 连接远程mysql服务器失败

php - 关于 mysqli 准备好的语句的问题

Mysql——一道简单的数据库设计题

Python 日期时间 工作日 strftime() 与 weekday()

php - 如何使用 Codeigniter 以行跨度显示 mysql 数据?