两个表的联合 - 两个表的交集

时间:2012-01-15 14:00:11

标签: sql sqlite

我有以下表格;

 A   B                       A   B
 _____                       _____
 1   t                       7   a
 2   r                       5   d
 3   e                       3   e
 4   f                       9   a
 5   d                       10  c
 6   s                       11  a
 7   a

而且,输出应该是;

 A   B                     
 _____                     
 1   t                      
 2   r                     

 4   f

 6   s

 9   a
 10  c
 11  a

换句话说,我想要真正不同的东西。我只能告诉this figure,看一看。我想要(工会B)。 我怎么能这样做?

6 个答案:

答案 0 :(得分:4)

此查询将执行此操作。它会加载两个表中的所有记录,然后显示所有那些存在的记录

SELECT
  A, B
FROM
  (SELECT A, B FROM TABLE1
   UNION ALL
   SELECT A, B FROM TABLE2)
  AS COMBINED
GROUP BY
  A, B
HAVING
    COUNT(*) = 1
ORDER BY A;

答案 1 :(得分:1)

SELECT f.A, f.B
FROM firstTable f
LEFT JOIN secondTable s ON (f.A = s.A)
WHERE (s.A IS NULL)
UNION
SELECT s.A, s.B
FROM firstTable f
RIGHT JOIN secondTable s ON (f.A = s.A)
WHERE (f.A IS NULL)

答案 2 :(得分:0)

SELECT iResult.* 
FROM
    (SELECT A, B
    FROM tableA
    WHERE A NOT IN
        (SELECT Distinct A FROM tableB)
    UNION
    SELECT A, B
    FROM tableB
    WHERE A NOT IN
        (SELECT Distinct A FROM tableB)) as iResult

答案 3 :(得分:0)

SELECT A, B
FROM Table1

UNION

SELECT A, B
FROM Table2

EXCEPT

SELECT t1.A, t1.B
FROM Table1 t1
  INNER JOIN Table2 t2 ON t1.A = t2.A AND t1.B = t2.B

答案 4 :(得分:0)

编辑删除之前的“解决方案”,因为我意识到它与Gary提出的解决方案相同。

(select a, b from table_1 minus 
 select a, b from table_2)       union
(select a, b from table_2 minus 
 select a, b from table_1);

这似乎适用于Oracle的后续数据:

create table table_1 (
  a number,
  b varchar(2)
);

create table table_2 (
  a number,
  b varchar(2)
);


insert into table_1 values  (1  ,'t');
insert into table_1 values  (2  ,'r');
insert into table_1 values  (3  ,'e');
insert into table_1 values  (4  ,'f');
insert into table_1 values  (5  ,'d');
insert into table_1 values  (6  ,'s');
insert into table_1 values  (7  ,'a');

insert into table_2 values  (7  ,'a');
insert into table_2 values  (5  ,'d');
insert into table_2 values  (3  ,'e');
insert into table_2 values  (9  ,'a');
insert into table_2 values  (10 ,'c');
insert into table_2 values  (11 ,'a');

答案 5 :(得分:-1)

简单地

SELECT a, b FROM table1 UNION SELECT a, b FROM table2;