postgresql - Postgres:如何按带时区的字符串日期排序?
问题描述
在我的 PostgreSQL 数据库中,我存储 JSONB,其中一个 JSON 节点是以下格式的日期字符串:
YYYY-MM-DD ,然后是 24 小时格式的小时、分钟和秒,然后是时区偏移量,如下所示:
2003-06-30 05:51:54+00:00 2003-06-30 14:25:45+10:00
但是,当我按 ASC 顺序对日期进行排序时,时间没有按时区偏移量正确排序,我认为这是因为 PostgreSQL 仍在查看日期,就好像它们是字符串一样。
SELECT header.id,
header.data ->> 'date' as "Date"
FROM all_messages.sci_math_headers header
WHERE header.data ->> 'msgid' = 'xyz'
OR header.data ->> 'ref' like '%xyz>%'
ORDER BY header.data ->> 'date' ASC
LIMIT 20;
因此,即使 2003-06-30 14:25:45+10:00 应该是第一个,它也会作为第二个结果出现。2003-06-30 05:51:54+00:00 2003-06-30 14:25:45+10:00
这是一个示例屏幕截图:
有没有办法直接在我的查询中将每个日期字符串转换为时间戳并正确排序?
解决方案
将您的字符串转换为真正的时间戳:
SELECT header.id,
header.data ->> 'date' as "Date"
FROM all_messages.sci_math_headers header
WHERE header.data ->> 'msgid' = 'xyz'
OR header.data ->> 'ref' like '%xyz>%'
ORDER BY (header.data ->> 'date')::timestamptz ASC -- Changes here
LIMIT 20;
应该工作。
推荐阅读
- java - 在 Java 中查找两个日期范围之间的交集(以编程方式)
- c# - 在 C# 中将对象数组隐式转换为 int 数组
- r - 大型网络人物
- generics - 浮点和双精度的 Kotlin 通用函数
- java - java.sql.SQLException:月
- python - 从 django 模板中的日期中删除引号
- flutter - 跨多个屏幕使用的 Flutter Stateful Widget 正在重建
- chef-infra - 厨师客户端错误:Errno::ENOENT:没有这样的文件或目录@ rb_sysopen - /etc/chef/chef_guid
- java - 如何在 Android Oreo 中获取字符串的 Base64 表示
- javascript - 构建动态 BottomNavigation NS 6.5 的问题