我可以使用模数来指定postgres中的间隔吗?

时间:2014-03-06 12:00:29

标签: sql postgresql

我必须列出上次更新后两年内未更新的项目。这是每天一次作为cron作业运行。

我知道我可以用丑陋的东西来做这件事:

SELECT art_id, art_update FROM items 
WHERE art_update = now()::date - interval '2 years'
OR art_update = now()::date - interval '4 years'
OR art_update = now()::date - interval '6 years'
OR art_update = now()::date - interval '8 years'
OR art_update = now()::date - interval '10 years';

有没有办法通过检查模数间隔来避免这种情况?还是用其他一些概括的方式来表达这个?

3 个答案:

答案 0 :(得分:1)

select art_id, art_update
from items 
where art_update in (
    (now() - interval '2 years')::date,
    (now() - interval '4 years')::date,
    (now() - interval '6 years')::date,
    (now() - interval '8 years')::date,
    (now() - interval '10 years')::date
);

select art_id, art_update
from items 
where art_update in (
    select d::date
    from generate_series (
        now() - interval '2 years',
        now() - interval '10 years',
        - interval '2 years'
    ) d(d)
);

http://www.postgresql.org/docs/current/static/functions-srf.html

答案 1 :(得分:1)

你可以试试这个。

SELECT art_id, art_update
FROM items
    Where int4(date_part('year', art_update)) % 2 = 0;

答案 2 :(得分:0)

您可以从今天(到下面的10年前)以2年为间隔生成一系列日期,并将其加入到您的桌面中:

SELECT i.art_id, i.art_update
FROM items i
    INNER JOIN generate_series(2, 10, 2) s (years)
        ON i.art_update = now()::date - interval '1 years' * s.years;

<强> Example on SQL Fiddle

N.B 如果你在系列中生成日期而不是数字,这似乎会略微加快:

SELECT i.art_id, i.art_update
FROM items i
    INNER JOIN generate_series(now() - interval '10 years', 
                                now() - interval '2 years', 
                                interval '2 years') d (d)
        ON art_update = d.d::date;