如果您遇到表单相关的问题
select * from foo
where created_on::date = '2014/1/1'
或者
select * from foo
where date_trunc('day', created_on) = '2014/1/1'
或者
select * from foo
where date(created_on) = '2014/1/1'
在什么情况下,不同的查询会表现得更好/更差?这三种选项中哪一种最高效?
如果您遇到表单相关的问题
select * from foo
where created_on::date = '2014/1/1'
或者
select * from foo
where date_trunc('day', created_on) = '2014/1/1'
或者
select * from foo
where date(created_on) = '2014/1/1'
总结评论,您的第一和第三种解决方案是相同的。根据@Nick Barnes的说法,将其转换为日期只是使用了date
函数。
这些选项以及第二个选项都需要对表中的每一行运行一个函数,因此即使您有索引,也无法使用它。
假设在created_on
上有索引,那么这是您最好的选择:
select * from foo
where created_on >= '2014/1/1 00:00:00'
and created_on < '2014/1/2 00:00:00';
date()
是用于实现::date
转换的函数。请参见:SELECT castfunc :: regprocedure FROM pg_cast WHERE castsource ='timestamp' :: regtype AND casttarget ='date' :: regtype
。 - Nick Barnestimestamp
索引的,但请记住,BETWEEN
包括其两个端点。您可能希望改用显式的>=
/<
比较。 - Nick Barnes