PostgreSQL 中的 YYYY-MM 列类型

YYYY-MM column type in PostgreSQL

我需要一个与月份和 table 中的用户关联的值。我想对其执行查询。不知道有没有适合这种需求的列数据类型。如果不是,我应该:

objective 用于 运行 查询,例如 (pseudo-SQL):

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

我建议不要对这个问题考虑太多,只使用本月的第一个 date/time。 Postgres 有很多特定于日期的函数——从 date_trunc()age() 再到 + interval —— 来支持日期。

您可以轻松地将它们转换为您想要的格式,获取两个值之间的差异,等等。

如果您将查询表述为:

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

然后它可以很容易地利用 (user_id, year_month)(year_month, user_id) 上的索引。

如果您对以 YYYY-MM 格式显示值感兴趣,可以使用 to_char(your_datatime_colum,'YYYY-MM')

示例:

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