PostgreSQL: Select data with a like on timestamp field

后端 未结 5 1114
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 16:29

I am trying to select data from a table, using a \"like\" on date field \"date_checked\" (timestamp). But I have this error :

SQLSTATE[42883]: Undefined func         


        
相关标签:
5条回答
  • 2020-12-23 17:14

    Perhaps the date_trunc function would be more to your liking:

    ... WHERE date_trunc('month', my_table.date_checker) = '2011-01-01'
    

    You can also put an index on that expression, if needed.

    0 讨论(0)
  • 2020-12-23 17:18

    It's all very well not "wanting to use" < and > with timestamps, but those operators can be converted into index scans, and a string-match... well, it can, but EWWWW.

    Well, the error is occurring because you need to explicitly convert the timestamp to a string before using a string operation on it, e.g.:

    date_checker::text LIKE '2011-01-%'
    

    and I suppose you could then create an index on (date_checker::text) and that expression would become an index scan but.... EWWWW.

    0 讨论(0)
  • 2020-12-23 17:25

    I don't believe you can do a like on a date column without converting it to a string representation first.

    You can use the between query to select between two dates, for instance:

    SELECT id FROM my_table WHERE date_checker BETWEEN '2011-01-01' AND '2011-02-01';
    
    0 讨论(0)
  • 2020-12-23 17:26

    Try this:

    SELECT my_table.id
    FROM my_table
    WHERE CAST(my_table.date_checker AS VARCHAR) LIKE '2011-01-%';
    
    0 讨论(0)
  • 2020-12-23 17:33

    If you need to do a comparison on some part of a timestamp, it's far better to use the EXTRACT() function. For example:

    WHERE EXTRACT(YEAR FROM date_checker) = 2011
    AND EXTRACT(MONTH FROM date_checker) = 1
    

    Details of the different "fields" you can extract from a date are in the documentation.

    0 讨论(0)
提交回复
热议问题