How to set '5 day' (datetime interval) in jdbc for PostgreSQL?

自闭症网瘾萝莉.ら 提交于 2021-02-07 14:18:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!