0

假设我有两张桌子:

TableA
ID,    Time,   Size

0      5:00    600
1      8:00    800
2      7:00    100
3      1:50    140
4      2:40    300 
12     3:40    300

TableB
ID,    Time,   Size

8      5:00    600
1      8:00    800
2      8:00    900
3      1:50    140
5      2:40    300 
12     3:40    300 

现在我想比较这两个表:给出表 A 和 B 中 ID 相同的所有行(或者让我们说两个表中存在 ID 的位置)但低于 12 - 这样就会踢出表 AID 0, 4, 12并从表 BID 8, 5, 12

之后,我将只剩下 3 行。现在我想踢出整个 TableA 行 ID == TableB 行 ID 之间存在一个或多个差异的所有行

最后会有(如果我认为正确的话)作为输出:

ID,    Time,   Size
1      8:00    800
3      1:50    140

对于这个解决方案,我需要确定相交并且可能是负数。起初我认为这个 SQL 语句会做我想做的事:

select * from TableA where ID < 12 intersect select * from TableB where ID < 12 
minus 
select * from TableB where ID < 12;

But this is not working that well. Ist because of the intersect, Im using intersect for the whole row, I should use intersect for only the IDs and IF I have the intersect of the IDs (that would be 1,2,3) then I have to use ID TableA with ID 1,2,3 minus TableB with ID 1,2,3. But how? Or do I miss something? Any ideas? Thank you

4

2 回答 2

3

From your requirements and the testdata you've provided, you don't need intersect at all. A mere INNER JOIN would suffice.

SELECT a.* 
FROM   TableA a 
       INNER JOIN TableB b ON b.ID = a.ID AND b.Time = a.Time AND b.Size = a.Size
于 2012-05-29T14:15:09.880 回答
1
select id from TableA where ID < 12 and id in (Select id from TableB)
union 
select id from TableB where ID < 12   and id in (Select id from TableA)

or

SELECT id, 
       time, 
       size 
FROM   (SELECT * 
        FROM   tablea 
        WHERE  id < 12 
        UNION ALL
        SELECT * 
        FROM   tableb 
        WHERE  id < 12) a 
GROUP  BY id, 
          time, 
          size 
HAVING Count(*) = 2 

or

SELECT * 
FROM   tablea A 
WHERE  EXISTS (SELECT 1 
               FROM   tableb b 
               WHERE  b.id = a.id 
                      AND b.time = a.time 
                      AND b.size = a.size) 
于 2012-05-29T14:14:21.980 回答