如何在PostgreSQL数据库中使用DAY函数?
我对 MySQL 数据库有这个查询:
Article.where('DAY( created_at ) = DAY( ? )', day)
我尝试在 PostgreSQL 数据库中也使用上面的查询,特别是我正在尝试这样的事情:
Article.where("DATE_PART('day', created_at) = DATE_PART('day', ?)", today)
但我收到错误 PGError: ERROR: function date_part(unknown,unknown)不是唯一的
为什么会出现这个错误?我以为我有文档的语法......
I have this query for MySQL database:
Article.where('DAY( created_at ) = DAY( ? )', day)
And I try to use the query above also in the PostgreSQL database, specifically I am trying something like this:
Article.where("DATE_PART('day', created_at) = DATE_PART('day', ?)", today)
But I am getting the error PGError: ERROR: function date_part(unknown, unknown) is not unique
Why is there that error? I thought I have the syntax by documentation...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来
今天
是一个模式YYYY-MM-DD
的字符串。您可以只提取最右边的两个字符,而不是转换为日期然后提取数字。会更快更简单:right( )
需要 PostgreSQL 9.1 或更高版本。在旧版本中,您可以替换:因为您需要字符 9 和 10。
这也应该有效:
注意,您必须将
'2012-01-16'
转换为date
,而不是间隔
。'2012-01-16'::interval
毫无意义。It seems
today
is a string of the patternYYYY-MM-DD
. You could just extract the rightmost two characters, instead of casting to date and then extracting a number. Would be faster and simpler:right()
requires PostgreSQL 9.1 or later. In older version you can subsitute:Because you want characters 9 and 10.
This should work, too:
Note, that you must cast
'2012-01-16'
todate
, not tointerval
.'2012-01-16'::interval
would be nonsense.根据 文档 有两个函数:
date_part (文本,时间戳)
date_part(文本,间隔)
因此数据库无法选择您想要的。将第二个参数转换为时间戳,例如:
According to the documentation there are two functions:
date_part(text, timestamp)
date_part(text, interval)
so database cannot choose which one you want. Cast the second parameter to timestamp, e.g. like this: