0

我正在尝试从 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 专家,所以我想问问社区是否有任何我不知道的“陷阱”。

4

3 回答 3

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您的第一个查询工作正常,但当您想过滤一天的数据时可能不需要使用。

于 2013-09-26T19:41:47.307 回答
0

使用中间,但从结束日期减去一秒。

insert_date between trunc(CURRENT_DATE-1) and trunc(CURRENT_DATE) - 1/86400
于 2013-09-26T19:42:30.800 回答
0
to_Timestamp(Concat (to_char(CURRENT_DATE-1),' 12:00:00 AM')) 

是非常多余的,我认为这是另一种方法的原因(trunc(current_date-1)

我能看到的唯一“问题”是,日期正好为上午 12:00:00 的记录将包含在第二个查询中,但不包含在第一个查询中。

有一种非常简单的方法可以检查此类问题:

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';

如果您从这些查询中的任何一个获得结果,则意味着两种方法不完全相等。

于 2013-09-26T19:44:22.107 回答