加入id不相等的两个表

时间:2017-11-14 18:58:08

标签: sql sql-server

我正在努力获取此查询以生成我想要的结果。

我有:

table1,columns = empid,alt_id

table2,columns = empid,alt_id

我想从表1中获取empid和alt_id,其中alt_id与table2中的alt_id不匹配。他们都会有alt_id数字,我只想得到那些不匹配的数字。

有什么想法吗?

5 个答案:

答案 0 :(得分:1)

SELECT * FROM table1
INNER JOIN table2 ON table2.empid = table1.empid AND table2.alt_id <> table1.alt_id

答案 1 :(得分:0)

这究竟意味着什么?通常在询问时,它的格式为“我希望A中的所有行在B中没有行匹配,B中所有行在A中都没有匹配”

看起来像这样:

SELECT * FROM
  A
  FULL OUTER JOIN
  B
  ON
    a.id = b.id

对于任何行数据,您会看到null,而另一行没有匹配的行:

A.id
1
2

B.id
1
3

Result of full outer join:

A.id B.id
1    1
2    null
null 3

然而,你要求A-B加入ID不相等的地方,这将是更无用的查询:

SELECT * FROM
  A
  INNER JOIN
  B
  ON
    a.id != b.id

看起来像是:

A.id B.id
1    3
2    1
2    3

答案 2 :(得分:0)

您似乎想要not exists

select t1.*
from table1 t1
where not exists (select 1 from table2 t2 where t2.alt_id = t1.alt_id);

目前还不清楚你是否也想加入empid,所以你可能真的想要:

select t1.*
from table1 t1
where not exists (select 1 from table2 t2 where t2.alt_id = t1.alt_id and t2.empid = t1.empid);

答案 3 :(得分:0)

A left join will find all records in Table A that do not match those in Table B.  Then use a Where filter to find the Nulls from Table B.  That will give you all those in A that do not have a matching ID in B.    

    Select A.*
    from Table A
    Left Join
    Table B
    on a.altid = b.altid
    where b.altid is null;

答案 4 :(得分:0)

从[登录]中选择* L内部联接员工E在l.EmployeeID = e.EmployeeID其中 l.EmployeeID不在(从员工中选择EmployeeID)