2011-05-18 42 views
3

我有一个表是这样的:我可以检查两个子查询返回相同的结果而不使用存储过程吗?

ObjId OtherObjId active (bool) 
1   5  0 
1   7  1 
1   9  0 
2   6  0 
... 
... 
... 
54   5  0 
54   7  1 
54   9  0 

这两个查询返回相同的结果:

select OtherObj2,active from MyTable where ObjId1 = 1; 

select OtherObj2,active from MyTable where ObjId1 = 54; 

我想运行返回如果两个查询结果是相同返回true单查询如果不是,则为false。

该表是一个配置表,如果两个对象具有相同的配置,我想轻松地进行测试。我可以使用商店程序执行检查,但是我想避免使用它。

我想不出一种方法来检查它使用查询,我想知道如果这是可能的。

任何提示?

感谢您的帮助。

+0

+1好问题,正是我在找的东西。 – Josh 2014-01-17 16:32:53

回答

5

不知道,如果你的DBMS支持except,但如果这样做,你可以用这个。

select OtherObjId, active 
from MyTable 
where ObjId = 1 
except 
select OtherObjId, active 
from MyTable 
where ObjId = 54 
4

你可以使用减

(select OtherObj2,active from MyTable where ObjId1 = 1 
minus 
select OtherObj2,active from MyTable where ObjId1 = 54 
) 
union 
(select OtherObj2,active from MyTable where ObjId1 = 54 
minus 
select OtherObj2,active from MyTable where ObjId1 = 1 
) 

不返回行,如果结果是一样的。

(同时需要短处,看是否QUERY1比QUERY2更多的行或者QUERY2比QUERY1多行)

2

如果你的数据库支持设置操作,使用EXCEPT(AKA MINUS):

select OtherObj2,active from MyTable where ObjId1 = 1 
EXCEPT 
select OtherObj2,active from MyTable where ObjId1 = 54 

这将导致一个空表,如果两者是相同的。

+0

这个我只相信sql服务器,Oracle没有。 – daven11 2011-05-18 12:53:37

+0

@ daven11 - Oracle称之为'MINUS'。 – Oded 2011-05-18 12:54:50

+1

你会发现except是不同的 - minus给出了A-B的结果,而except除了给出的是一个但不是另一个的行,它是(A-B)union(B-A)。 – daven11 2011-05-18 12:57:46

0

你可以尝试这样的事情。如果它返回任何记录,则查询结果不相同。如果它返回0条记录,则不存在不匹配。

select 
    OtherObjId, 
    Active 
from 
    MyTable 
where 
    ObjId in (1, 54) 
group by 
    OtherObjId, 
    Active 
having COUNT(*) < 2