我需要比较两列,两者都有sysdate作为值但是
select count(*) from (
(select col from tab1)
minus
(select col from tab2 ) ) --
给出1,但我希望它为0
让我进一步澄清:
create table tab1 (col date)
-- Can the datatype of `col` be something else
-- rather than `date` so that when `SYSDATE`
-- gets inserted to it, I get only `10-MAY-17`
-- rather than the date along with time?
-- I have control on this create statement,
-- I can create the table as I wish to.
insert into tab1 values (sysdate)
-- I have no control on this,
-- this is system generated .
create table tab2 (col date)
-- I have control on it.
-- I can modify it.
insert into tab2(col) values (sysdate)
-- I have control on it to change it
如果问题仍然不明确,请告诉我。 感谢
答案 0 :(得分:-1)
关于sysdate
的事情是,它返回当前的日期和时间。当我们比较一个日期列与另一个日期列时,我们正在比较日期和时间元素。如果日期具有不同的时间元素,则列将不匹配。
我怀疑这就是为什么你得到了你不想要的结果。幸运的是,解决方案非常简单:使用trunc()
从日期中删除时间元素。
SQL> select * from tab1;
COL
-------------------
2017-05-09 03:25:45
2017-05-09 06:30:32
2017-05-09 12:20:47
SQL> select * from tab2;
COL
-------------------
2017-05-09 14:12:10
2017-05-09 15:25:59
SQL> select count(*) from (
2 (select trunc(col) from tab1)
3 minus
4 (select trunc(col) from tab2))
5 /
COUNT(*)
----------
0
SQL>
基于后续修订的替代解决方案:
create table tab1 (col date)
-col
的数据类型是否可以是其他内容 - 而不是date
以便SYSDATE
时 - 插入它,我只得到10-MAY-17
- 而不是日期和时间?
- 我控制了这个创建声明,
- 我可以按照自己的意愿创建表格
在tab1
create or replace trg_tab1
before insert or update on tab1
begin
:new.col := trunc(:new.col);
end;
这将从col
删除时间元素。
insert into tab2(col) values (sysdate)
- 我可以控制它来改变它
只需在插入
时应用截断insert into tab2(col) values (trunc(sysdate))
或者像上面那样在tab2
上构建一个触发器。
现在,您在两个表中都有具有纯日期的记录,因此您的原始减号查询无需修改即可运行。
关于猜测性质的说明
我对此问题的假设是,这是某种形式的流程检查:tab1
表示某些初始状态,发生了某些事情,并且在流程完成时填充了tab2
。如果是这样,也许OP的查询意味着检查没有未处理的记录。
显然,我们可以考虑采用更好(更强大,更准确)的方法来实施这样的流程,但问题并没有向我们提出要求。是的,我同意Seekers应该解释他们试图实施的业务逻辑,而不是期望我们对其进行逆向工程。
答案 1 :(得分:-1)
为了从您编写的查询中获得0,您可以使用:
create table tab1 (col date);
create table tab2 (col date);
insert all
into tab1(col) values (sysdate)
into tab1(col) values (sysdate)
SELECT * FROM dual;
commit;
此外,minus
运算符将为您提供tab1中存在的行,而不是tab2中的行。您可能还需要以相反的方式了解结果。在这种情况下使用:
select count(*) (
select .. from tab1 minus select .. from tab2
union all
select .. from tab2 minus select .. from tab1)
这将显示两个表中的不匹配,而不仅仅是第一个表。