使用extract(month from the_date)而不是to_char. 请参阅Pg 文档中的日期时间函数。
与to_char您一起,您将遇到各种案例、本地化等问题。
假设你的意思是数据类型effective_date是timestampor 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_charMonMon
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 注入。