代码之家  ›  专栏  ›  技术社区  ›  Santhosh

postgresql:以文本形式存储的时间。如何查询时间

  •  0
  • Santhosh  · 技术社区  · 4 年前

    device table:
    
    column        Type
    id            integer
    created       text
    name          text
    

    这里时间存储在 text 键入而不是 timestamp

    如: created 12/19/2020 20:40:23

    我试着查询这个日期和时间。

    SELECT "device"."id",
           "device"."created",
           "device"."name",
    FROM "device"
    WHERE "device"."created" < '12/19/2020 20:40:23'
    LIMIT 21
    

    那么,在这种情况下,哪种最佳的解决方案可以获得以文本形式存储的w.r.t时间数据呢

    1 回复  |  直到 4 年前
        1
  •  0
  •   Bjarni Ragnarsson    4 年前

    您需要将文本转换为时间戳。在这种情况下,一个简单的转换就足够了。

    SELECT device.id,
           device.created,
           device.name,
    FROM device
    WHERE device.created::timestamp < '12/19/2020 20:40:23'
    LIMIT 21
    
        2
  •  1
  •   Stefanov.sm    4 年前

    这是因为字符串是按字典顺序比较的。使用 to_timestamp 使用格式规范字符串将文本转换为时间戳,然后比较时间戳。
    ISO-8601 然后可以将它们直接转换为timestamp。
    将时间戳存储为格式化文本。

    SELECT id, created, name
    FROM device
    WHERE to_timestamp(created, 'mm/dd/yyyy hh24:mi:ss') < '2020-12-19 20:40:23'::timestamp
    LIMIT 21;
    

    顺便说一句,你不需要报价。