我在2009-11-25, 12:42AM IST
名为“Post”的表中以字符串形式在名为“postingdate”的字段中有一个值。
我需要查询来根据日期范围获取详细信息。我尝试了以下查询,但它引发了错误。请指导我解决此问题。提前致谢。
select postingdate
from post
where TO_DATE(postingDate,'YYYY-MM-DD')>61689
and TO_DATE(postingDate,'YYYY-MM-DD')<61691
我在2009-11-25, 12:42AM IST
名为“Post”的表中以字符串形式在名为“postingdate”的字段中有一个值。
我需要查询来根据日期范围获取详细信息。我尝试了以下查询,但它引发了错误。请指导我解决此问题。提前致谢。
select postingdate
from post
where TO_DATE(postingDate,'YYYY-MM-DD')>61689
and TO_DATE(postingDate,'YYYY-MM-DD')<61691
正如您现在所看到的,尝试对表示日期的字符串列执行任何类型的查询都是一个问题。你有几个选择:
将 postingdate 列转换为某种 DATE 或 TIMESTAMP 数据类型。我认为这是您的最佳选择,因为它将使使用该字段查询表更快、更灵活且不易出错。
将postingdate 保留为字符串,并在进行比较时使用函数将其转换回日期。这将是一个性能问题,因为除非您的数据库支持基于函数的索引,否则大多数查询将变成全表扫描。
将postingdate 保留为字符串并将其与其他字符串进行比较。这不是一个好的选择,因为我认为您已经找到了一种以这种方式进行范围查询的方法。
如果是我,我会转换数据。祝你好运。
If it's really a string, you're lucky that it's in YYYY-MM-DD format. You can sort and compare that format as a string, because the most significant numbers are on the left side. For example:
select *
from Posts
where StringDateCol between '2010-01-01' and '2010-01-02'
There's no need to convert the string to a date, comparing in this way is not affected by the , 12:42AM IST
appendage. Unless, of course, your table contains dates from a different time zone :)
在 SQL Server 中,您可以说
Select postingdate from post
where postingdate between '6/16/1969' and '6/16/1991'
在对其运行日期范围查询之前,您需要将字符串转换为日期。如果您对时间部分不感兴趣,您可以只使用字符串。
实际功能将取决于您的 RDBMS
for strings only
select * from posts
where LEFT(postingDate,10) > '2010-01-21'
or
for datetime ( Sybase example)
select * from posts
where convert(DateTime,postingDate) between '2010-01-21' and '2010-01-31'