2013-01-08 163 views
0

(例如,通过比较两个表

简化的情况表:

Table A which contain the missing row entry in table B

select count(1) from table_a; --> returns 5 results 
select count(1) from table_b; --> returns 4 results 
select count(1) from table_a, table_b2 b 
where b.id_ab like a.id_ab; --> returns 4 results 
select count(1) from table_a, table_b2 b 
where b.id_ab not like a.id_ab; --> returns unexpected result 

SQL:

尝试这样做(除了),但遇到错误。

select a.id_ab from table_a a, table_b b except select a.id_ab from table_a, table_b2 b 
where b.id_ab not like a.id_ab; 

或如何使用union来做到这一点?例如

(Select * from table_a except select * from table_b) Union All (Select * from table_b  except select record_id from table_a); 

预期结果:

results

谢谢。

回答

2
select a.id_ab 
from table_a a 
    LEFT JOIN table_b b on a.id_ab = b.id_ab 
where b.id_ab is null 
+0

感谢legendofawesomeness。完美的作品。 – user1872384

1

使用下面的查询(添加左外连接)。

它会得到在table_a中不匹配的数据。

select count(1) from table_a, table_b2 b 
where b.id_ab(+) = a.id_ab; 

如果妳如果您使用查询列之间的UNION应该是平等的希望只缺下面的查询

select count(1) from table_a, table_b2 b 
where b.id_ab <> a.id_ab; 

行使用。

SELECT col1,col2 from table_a 
    UNION 
    SELECT col1,col2 from table_b 

但不喜欢

SELECT col1,col2 from table_a 
    UNION 
    SELECT col1 from table_b 
+0

感谢联盟Viru的提示 – user1872384