问题
Considering the following example
select * from foo where time +'10 day' >current_timestamp
I would like to make this query parametrized for Java, and I don't know how to set the 10 day
?! (String doesn't work)
回答1:
select * from foo where time +'10 day'::interval >current_timestamp;
回答2:
You may either pass a String parameter and cast it, e.g.
select * from foo where (time + CAST(? AS interval)) > current_timestamp
or pass an int parameter multiplied by a fixed interval, which is better if you're always working with days not more complex intervals. E.g.
select * from foo where (time + ? * INTERVAL '1' DAY) > current_timestamp
with a setInt
parameter.
回答3:
Be sure to write the query like this:
SELECT * FROM foo WHERE "time" > current_timestamp - interval '1 day' * n
The point is to compare the column to an expression, so the whole thing is sargable and an index can be used.
Either pass a the readily calculated timestamp
for current_timestamp - interval '10 days'
, or pass an integer for n
.
And I would not use time
as column name, which is a reserved word in the SQL standard.
More about date / time arithmetic in the manual.
来源:https://stackoverflow.com/questions/24998959/how-to-set-5-day-datetime-interval-in-jdbc-for-postgresql