两个表中值不匹配的行

时间:2018-08-10 01:51:25

标签: sql sql-server oracle join

我有两个表T1:

+----+-----+--------------------+----------+
| ID | emp |     manager        |     proj |
+----+-----+--------------------+----------+
|  1 | Sam |     Tom            |       aa |
|  1 | Sam |     Tom            |       bb |
|  1 | Sam |     Tom            |       cc |
|  1 | Sam |     Tom            |       dd |
+----+-----+--------------------+----------+

表T2:

+--------+---------+--------+-----------+
| Course |  Type   | proj   | Category  |
+--------+---------+--------+-----------+
| XYZ    |     NEW |     aa |    a      |
| DWE    |     OLD |     bb |    b      |
| RTY    |     OLD |     ii |    c      |
| UIO    |     NEW |     gg |    d      |
+--------+---------+--------+-----------+

输出:

+-----------+-----+----------+--------+---------+---------+----------+
|    ID     | emp |  manager |  proj  | Course  |  Type   | Category |
+-----------+-----+----------+--------+---------+---------+----------+
|         1 | Sam |  Tom     |     ii |     RTY |     OLD |     c    |
|         1 | Sam |  Tom     |     gg |     UIO |     NEW |     d    |
+-----------+-----+----------+--------+---------+---------+----------+

我有一个常见的col proj,表1由emp完成,而table2由emp完成,没有由emp完成,带有附加字段。我想从table2中获取所有不匹配的行,但具有上述表1中的属性。有人可以帮助执行SQL查询吗?

3 个答案:

答案 0 :(得分:0)

尝试

with a as (
select T2.* from T1 right join T2 
on T1.proj=T2.proj
where T1.proj is null) ,

 b as (select T1.id, T1.emp, t1.manager from T1 left join T2 
on T1.proj=T2.proj
group by T1.id, T1.emp, t1.manager,T2.proj
having T2.proj is null)

select * from a cross join b

答案 1 :(得分:0)

select e.ID, e.emp, e.manager, t2.proj, t2.Course, t2.Type as Name, t2.Category
from t2
cross join (select distinct ID, emp, manager from T1) e
where not exists(select * from t1 where t1.prog=t2.proj)

答案 2 :(得分:0)

选择tbl.ID,tbl.emp,tbl.manager,t2.proj,t2.Course,t2.Type作为Name,t2.Category
从 ( 选择t2.ID,t2.emp,t2.manager 从表2 t2 不存在的地方(从表1 t1中选择1,其中t1.proj = t2.proj) )tbl 交叉应用表1 t1