如何按自定义字段 iso8601 值获取主题?

limit(10) 应该已经可以实现这一点 :slight_smile:

类似这样的代码应该可以(但未经测试):

Topic.where("category_id in (?)", [cat_id])
         .where("closed = ?", false)
         .joins("LEFT JOIN topic_custom_fields import_tcf ON import_tcf.topic_id = topic.id AND topic_custom_fields.name = 'importedSortDate'")
         .order("TIMESTAMP import_tcf.value")
         .order("created_at desc")
         .limit(10)

问题在于,要求 PostgreSQL 将日期字符串转换为时间戳会非常低效。它必须对每个主题先进行转换,然后再选取前 10 个。

我想到有几个解决方案:你可以将日期存储为“自纪元以来的秒数”,而不是 ISO8601 格式。这将使 PostgreSQL 对其排序容易得多。或者,你也可以使用数据库迁移为 topic_custom_fields 表的 TIMESTAMP value 添加索引。