日期范围之间的PostgreSQL查询

编程入门 行业动态 更新时间:2024-10-26 20:24:18
本文介绍了日期范围之间的PostgreSQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图查询我的postgresql数据库,以返回日期在特定月份和年份的结果。换句话说,我想要一个月年的所有值。

I am trying to query my postgresql db to return results where a date is in certain month and year. In other words I would like all the values for a month-year.

到目前为止,我唯一能做到的方法是这样:

The only way i've been able to do it so far is like this:

SELECT user_id FROM user_logs WHERE login_date BETWEEN '2014-02-01' AND '2014-02-28'

问题是我必须在查询表之前计算第一个日期和最后一个日期。

Problem with this is that I have to calculate the first date and last date before querying the table. Is there a simpler way to do this?

谢谢

推荐答案

使用日期(和时间),如果您使用> = start AND<结束。

With dates (and times) many things become simpler if you use >= start AND < end.

例如:

SELECT user_id FROM user_logs WHERE login_date >= '2014-02-01' AND login_date < '2014-03-01'

在这种情况下,您仍然需要计算月份的开始日期

In this case you still need to calculate the start date of the month you need, but that should be straight forward in any number of ways.

结束日期也得到了简化;只需添加一个月即可。不用担心28、30、31等。

The end date is also simplified; just add exactly one month. No messing about with 28th, 30th, 31st, etc.

此结构还具有能够保持索引使用的优势。

This structure also has the advantage of being able to maintain use of indexes.

许多人可能会建议格式,如下所示,但它们 不 使用索引:

Many people may suggest a form such as the following, but they do not use indexes:

WHERE DATEPART('year', login_date) = 2014 AND DATEPART('month', login_date) = 2

这涉及到计算表中每一行的条件(扫描),而不是使用索引来查找将匹配的行的范围(寻求范围)。

This involves calculating the conditions for every single row in the table (a scan) and not using index to find the range of rows that will match (a range-seek).

更多推荐

日期范围之间的PostgreSQL查询

本文发布于:2023-10-16 12:25:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   PostgreSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!