SQL Select语句问题-有条件地返回第二个表上的行

SQL Select语句问题-有条件地返回第二个表上的行,sql,Sql,对于以下SQL Select语句场景,我确实需要一些帮助: 我需要有条件地选择表中的所有行,这取决于用户ID是否已将数据输入到具有相同ID的第二个表中 例如: 从表A中选择idNumber中未包含idNumber的所有行 表B 但对于表B中的每个idNumber,仍然返回行,除非 特定的用户ID位于表B的该行中。 用于排除=1111的记录的用户ID SQL查询应返回: idNumber|type|Date 1 A 01/01/01 2 A 01/0

对于以下SQL Select语句场景,我确实需要一些帮助:

我需要有条件地选择表中的所有行,这取决于用户ID是否已将数据输入到具有相同ID的第二个表中

例如:

从表A中选择idNumber中未包含idNumber的所有行 表B 但对于表B中的每个idNumber,仍然返回行,除非 特定的用户ID位于表B的该行中。 用于排除=1111的记录的用户ID

SQL查询应返回:

idNumber|type|Date

   1      A    01/01/01

   2      A    01/01/01

   3      B    01/01/01

   5      B    01/01/01
我为这篇冗长的文章道歉,但我希望它有意义

多谢各位, ukjezza

看起来像一个左连接,联合可以处理它:

SELECT a.* 
FROM TableA as a
LEFT JOIN TableB as b
ON a.idNumber = b.idNumber
WHERE COALESCE(b.userID, -1) != 1111
另一种选择:

Select TableA.idNumber, TableA.type, TableA.Date
From TableA
    Left Join TableB
        On TableB.idNumber = TableA.idNumber
            And TableB.userId = 1111
Where TableB.idNumber Is Null

你知道这与使用连接相比性能如何吗?@Abe Miessler-取决于数据库和数据的性质。如果TableB与TableA相比是巨大的,那么Exists子句将再次表现得更好,这取决于db。如果两个表的大小大致相同,那么连接的性能可能会更好。我注意到SQLServer比MySQL更好地处理现有函数。MySQL需要一个In子句而不是Exists函数。谢谢大家,我现在有了一个解决方案,并且我已经学会了许多有条件地选择数据的新方法。事实上,我同意:选择idNumber,type,DateFrom tableA此处不存在从TableB中选择1,其中TableB.idNumber=bleA.idNumber和TableB.userID=1111再次感谢!!!!
select A.*
from TableA as A
  left outer join TableB as B
    on A.idNumber = B.idNumber
where B.idNumber is null or
      B.userID <> '1111'
Select idNumber, type, Date
From TableA
Where Not Exists    (
                    Select 1
                    From TableB
                    Where TableB.idNumber = TableA.idNumber
                        And TableB.userID = 1111
                    )
Select TableA.idNumber, TableA.type, TableA.Date
From TableA
    Left Join TableB
        On TableB.idNumber = TableA.idNumber
            And TableB.userId = 1111
Where TableB.idNumber Is Null