我知道您可以使用date() function将日期时间转换为日期:
sqlite> select date('2000-01-01 10:00:00');
2000-01-01
但是为什么SQLite3's cast expression如
sqlite> select cast('2000-01-01 10:00:00' as date);
2000
只返回年份?
即使使用显式的datetime()设置,也仅返回年份:
sqlite> select cast(datetime('2000-01-01 10:00:00') as date);
2000
或者:
sqlite> select cast(datetime('now') as date);
2019
看看Postgresql,它可以正确解决这两个问题:
postgresql> select date('2000-01-01 10:00:00');
2000-01-01
postgresql> select cast('2000-01-01 10:00:00' as date);
2000-01-01
SQLite3的技术解释是什么-我想不到-行为如何?
答案 0 :(得分:3)
对于SQLite,没有Date
数据类型。如其文档中所述:https://www.sqlite.org/datatype3.html
您用作Date
的实际上是TEXT
。
您可以检查:
select typeof(datetime('now'));
返回:
text
并且:
select typeof(cast(datetime('now') as date));
返回:
integer
所以cast('2000-01-01 10:00:00' as date)
的结果是一个整数,并且相同
您获得的整数:
select '2000-01-01 10:00:00' + 0
当SQLite隐式将'2000-01-01 10:00:00'
转换为2000
以便在数学运算中使用它时。
对于日期而言,它恰好是年份的数值,但通常SQLite返回TEXT的最长子字符串,从第一个字符开始,可以表示为整数。
因此,对于'2000-01-01 10:00:00'
,它是直到第一年-
(即年份)的子字符串。