首页 > 解决方案 > 如何删除时间戳等于 2018 的记录

问题描述

我有一个带有 table 的 Postgres 数据库absences。我正在尝试删除时间戳中包含“2018”的所有记录,如下所示:

DELETE FROM absences WHERE date LIKE '%2018%';

但我收到此错误消息:

absence-registrator_production=> DELETE FROM absences WHERE date LIKE '2018%';
ERROR:  operator does not exist: timestamp without time zone ~~ unknown
LINE 1: DELETE FROM absences WHERE date LIKE '2018%';

有谁知道如何从缺勤表中删除日期字段中包含“2018”的记录?

标签: sqlpostgresqldate-arithmetic

解决方案


另一种选择是使用可能使用该列上的索引的条件:

where date >= timestamp '2018-01-01 00:00:00' 
  and date < timestamp '2019-01-01 00:00:00';

如果您不想写一个长的“时间戳文字”并且只是将一个数字传递给查询,您可以使用make_timestamp()

where date >= make_timestamp(2018,1,1,0,0,0) 
  and date < make_timestamp(2019,1,1,0,0,0);

如果该值是您可以使用的参数:

where date >= make_timestamp(?,1,1,0,0,0) 
  and date < make_timestamp(? + 1,1,1,0,0,0);

提取功能也可以工作:

where extract(year from date)::int = 2018

或使用 to_char()

where to_char(date, 'yyyy') = '2018'

推荐阅读