我正在尝试从ORACLE表中检索具有昨天日期的记录。我每天都有一份工作,只检索昨天的记录。
注意**列insert_date的类型为date
这是我到目前为止的两个SQL语句:
SELECT distinct column1
FROM table1
WHERE flag = 'N'
AND insert_date BETWEEN TRUNC(CURRENT_DATE-1) AND TRUNC(CURRENT_DATE)
AND ipaddress IS NOT NULL
AND ipaddress <> '0.0.0.0';
和
SELECT distinct column1
FROM table1
WHERE flag = 'N'
AND insert_date
BETWEEN To_Timestamp(CONCAT (to_char(CURRENT_DATE-1),' 12:00:00 AM'))
AND To_Timestamp(Concat (to_char(CURRENT_DATE-1),' 11:59:59 PM'))
AND ipaddress IS NOT NULL
AND ipaddress <> '0.0.0.0';
似乎这两个SQL语句产生相同的输出。但是,我不是ORACLE的专家,所以我想询问社区是否有任何我不知道的“陷阱”。
答案 0 :(得分:0)
试试这个:
SELECT distinct column1
FROM table1
WHERE flag = 'N' AND
insert_date = trunc(sysdate-1,'DD')
and ipaddress is not null and ipaddress<>'0.0.0.0';
您的第一个查询工作正常,但如果您想要过滤一天的数据,则可能不需要使用between
。
答案 1 :(得分:0)
使用中间值但从结束日期减去秒。
insert_date between trunc(CURRENT_DATE-1) and trunc(CURRENT_DATE) - 1/86400
答案 2 :(得分:0)
to_Timestamp(Concat (to_char(CURRENT_DATE-1),' 12:00:00 AM'))
是非常多余的,我认为这是另一种方法的原因(trunc(current_date-1)
)
只有“陷阱”我才能看到日期完全 12:00:00 am的记录将包含在第二个查询中但不包含在第一个查询中。
有一种非常简单的方法可以检查这类问题:
SELECT distinct column1
FROM table1
WHERE flag = 'N' AND insert_date between trunc(CURRENT_DATE-1)
and trunc(CURRENT_DATE) and ipaddress is not null and ipaddress<>'0.0.0.0';
MINUS
SELECT distinct column1
FROM table1
WHERE flag = 'N'
AND insert_date between To_Timestamp(Concat (to_char(CURRENT_DATE-1),' 12:00:00 AM')) and To_Timestamp(Concat (to_char(CURRENT_DATE-1),' 11:59:59 PM'))
and ipaddress is not null and ipaddress<>'0.0.0.0';
和
SELECT distinct column1
FROM table1
WHERE flag = 'N'
AND insert_date between To_Timestamp(Concat (to_char(CURRENT_DATE-1),' 12:00:00 AM')) and To_Timestamp(Concat (to_char(CURRENT_DATE-1),' 11:59:59 PM'))
and ipaddress is not null and ipaddress<>'0.0.0.0';
MINUS
SELECT distinct column1
FROM table1
WHERE flag = 'N' AND insert_date between trunc(CURRENT_DATE-1)
and trunc(CURRENT_DATE) and ipaddress is not null and ipaddress<>'0.0.0.0';
如果从这些查询中获得结果,那么这意味着两种方法并不完全相同。