我应该选择所有 7 月(或 07 年)出生的人。这没有用:
select * from people where date_trunc('month',dob)='07';
ERROR: invalid input syntax for type timestamp with time zone: "07" LINE 1: ...ct * from people where date_trunc('month',dob)='07';
什么是正确的方法?
最佳答案
to_char()
用于格式化日期。对于像你这样的情况,extract()
更简单更快:
SELECT *
FROM people
WHERE extract(month FROM dob) = 7;
如果要搜索
a specific year and month too (YYYY-MM)
...如评论中所述,像最初一样使用 date_trunc()
。只需将它与 date
或 timestamp
进行比较,而不是与字符串进行比较,这没有任何意义(并且是错误消息的原因)。查找 1970 年 7 月出生的人:
SELECT *
FROM people
WHERE date_trunc('month', dob) = '1970-07-01 0:0'::timestamp;
如果性能相关,将其重写为:
SELECT *
FROM people
WHERE dob >= '1970-07-01 0:0'::timestamp
AND dob < '1970-08-01 0:0'::timestamp; -- note the < with the upper limit
因为这种形式可以在 people.dob
上使用普通索引:
CREATE INDEX people_dob_idx ON people (dob);
... 因此会影响之前使用大表进行查询的性能。与小 table 无关紧要。
您还可以使用 functional index 来加快第一个查询的速度,如果需要的话。
关于postgresql - psql 8.4.1 选择特定月份出生的所有人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519869/