YYYY-MM column type in PostgreSQL

前端 未结 2 544
一生所求
一生所求 2021-01-19 08:11

I need to a value associated to a month and a user in a table. And I want to perform queries on it. I don\'t know if there is a column data type for this type of need. If no

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-19 08:18

    I would suggest not thinking too hard about the problem and just using the first date/time of the month. Postgres has plenty of date-specific functions -- from date_trunc() to age() to + interval -- to support dates.

    You can readily convert them to the format you want, get the difference between two values, and so on.

    If you phrase your query as:

    where year_month = date_trunc('month', now()) and user_id = 'adc1-23...'
    

    Then it can readily take advantage of an index on (user_id, year_month) or (year_month, user_id).

提交回复
热议问题