sql server inner连接两个表并过滤两个字段,获取额外的记录

时间:2017-05-30 13:59:35

标签: sql sql-server inner-join

我遇到了在两个表之间使用INNER JOIN获取SELECT以获得正确输出的问题。

SELECT *
FROM PERSON_TABLE
WHERE MYSOMETHINGID = 123

结果

ID   PERSON_ID     PERSON     IS_SELECTED    IS_BACKUP  MYSOMETHINGID 
2    -1            PERSON1    0              0          123
3    12            PERSON2    0              1          123
4    13            PERSON3    1              0          123
5    15            PERSON4    0              1          123
6    22            PERSON5    0              0          123

select *
from ASSIGNED_TABLE
where MYSOMETHINGID = 123

ID   PERSON_ID     PERSON     MYSOMETHINGID 
3    12            PERSON2    123
4    13            PERSON3    123
5    15            PERSON4    123

我想内部加入两家公司,只选择IS_SELECTED = 1的记录,如果PIGN_TABLE记录存在于ASSIGNED_TABLE

这是我的疑问

select *
from ASSIGNED_TABLE AT inner join
     PERSON_TABLE PT
     on PT.IS_SELECTED = 1 AND AT.PERSON_ID = PT.PERSON_ID
where AT.MYSOMETHINGID = 123

ID   PERSON_ID     PERSON     MYSOMETHINGID   IS_SELECTED   IS_BACKUP
3    12            PERSON2    123             1             0
4    13            PERSON3    123             1             0
5    15            PERSON4    123             1             0

我期待PERSON13,因为它是IS_SELECTED = 1的唯一记录。我不明白为什么我得到3条记录而不是1条而且奇怪的是所有3条记录的IS_SELECTED为1而所有IS_BACKUP为0 / p>

非常感谢任何帮助。感谢。

3 个答案:

答案 0 :(得分:0)

我认为您还需要加入mysomethingid

select *
from ASSIGNED_TABLE AT inner join
     PERSON_TABLE PT
     on PT.IS_SELECTED = 1 AND
        AT.PERSON_ID = PT.PERSON_ID AND
        AT.MYSOMETHINGID = PT.MYSOMETHINGID
where AT.MYSOMETHINGID = 123;

答案 1 :(得分:0)

试试这个

select *
  from ASSIGNED_TABLE AT 
 inner join PERSON_TABLE PT
  on AT.PERSON_ID = PT.PERSON_ID
 where PT.IS_SELECTED = 1 AND MYSOMETHINGID = 123

答案 2 :(得分:-1)

另一种方法是仅选择is_selected = 1

的行
select *
from ASSIGNED_TABLE AT inner join
 PERSON_TABLE PT ON
 AT.PERSON_ID = PT.PERSON_ID
where AT.MYSOMETHINGID = 123 AND PT.IS_SELECTED = 1