YYYY-MM column type in PostgreSQL

喜你入骨 提交于 2020-11-29 08:18:34

问题


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 not, should I:

  • Create a string field and build year-month concatenation (2017-01)
  • Create a int field and build year-month concatenation (201701)
  • Create two columns (one year and one month)
  • Create a date column at the beginning of the month (2017-01-01 00:00:00)
  • Something else?

The objective is to run queries like (pseudo-SQL):

SELECT val FROM t WHERE year_month = THIS_YEAR_MONTH and user_id='adc1-23...';

回答1:


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).




回答2:


If you are interested in display values in YYYY-MM formt you can use to_char(your_datatime_colum,'YYYY-MM')

example:

SELECT to_char(now(),'YYYY-MM') as year_month


来源:https://stackoverflow.com/questions/43657514/yyyy-mm-column-type-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!