使用extract(month from the_date)
而不是to_char
。请参阅datetime functions in the Pg docs。
随着to_char
你会遇到各种案件,本地化等问题。
假设你的意思是说的effective_date
的数据类型为timestamp
或date
,你会写:
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND extract(month from effective_date) = 7
AND deleted = 0";
如果是integer
然后 - 假设这是具有划时代意义的日期 - 你必须把它与转换为时间戳to_timestamp
,然后使用extract
就可以了。见epoch
部分连接到上面的文档,例如:
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND extract(month from to_timestamp(effective_date)) = 7
AND deleted = 0";
你的问题的直接原因是,你调用to_char(integer,text)
一个整数划时代的日期。只有timestamp
版本的to_char
做日期格式; Mon
对其他人不是特别的,所以它被简单地输出为字符串Mon
。比较:
regress=# SELECT to_char(current_timestamp, 'Mon');
to_char
---------
Aug
(1 row)
regress=# select to_char(extract(epoch from current_timestamp), 'Mon');
to_char
---------
Mon
(1 row)
记住参数化的现实世界的这些查询的版本,以帮助避免SQL injection。
挂上,你说'effective_date'有数据类型'integer'吗?不是'日期'?不是'时间戳'?你的问题是否是一个错误?如果它是一个整数,你期望如何得到一个日期?它是一个时代日期(自某个日期以来的秒数)? –
@克雷格抱歉,我的错。是的,这是一个时代的日期。 – Thili
那么,'to_char'会做什么?你在'psql'中试过了吗?让我们来看看:'select to_char(extract(current_timestamp的时期),'Mon')'只输出字符串“Mon”,它永远不会等于字符串“Jul”。所以你的问题是,你在调用'to_char'的整数版本,并期望它知道你想把整数作为一个日期。请参阅psql中的'\ df to_char'以查看所有'to_char'变体。只有'timestamp'的日期格式符合[documentation](http://www.postgresql.org/docs/current/static/functions-formatting.html) –