简体   繁体   English

SQL查询日期字符串按范围

[英]SQL query date string by range

Spec: I need to query by date month and day only (ignoring year) 规格:我只需要按日期月份和日期查询(忽略年份)

Input: 输入:

start := '2015-12-29'
end := '2016-01-03'

Output: 输出:

1986-12-30
1980-01-01
1982-12-31
1978-01-03
...

Current solution: 当前解决方案:

SELECT *
FROM users
WHERE RIGHT(birthday,5) >= $1
  AND RIGHT(birthday,5) <= $2

But this only works when the year not overlap, what's the easiest solution for this case? 但这仅在年份不重叠的情况下有效,这种情况最简单的解决方案是什么?

My simplest solution is by generating the SQL string using another language: 我最简单的解决方案是使用另一种语言生成SQL字符串:

if start_year == end_year {
    date_where = `
    AND RIGHT(birth_date,5) >= RIGHT(` + Z(start) + `,5)
    AND RIGHT(birth_date,5) <= RIGHT(` + Z(end) + `,5)
    `
} else {
    date_where = `
    AND ( RIGHT(birth_date,5) >= RIGHT(` + Z(start) + `,5)
        AND RIGHT(birth_date,5) <= '12-31'
    ) OR ( RIGHT(birth_date,5) >= '01-01'
        AND RIGHT(birth_date,5) <= RIGHT(` + Z(end) + `,5)
    )`
}

I believe there are better way than this.. 我相信有比这更好的方法了。

A date is not a string, don't use string functions to handle a date. 日期不是字符串,请勿使用字符串函数来处理日期。 Use date functions like EXTRACT : 使用日期函数,例如EXTRACT

SELECT  '2015-12-29'::date,
    EXTRACT(month from '2015-12-29'::date),
    EXTRACT(day from '2015-12-29'::date);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM