【问题标题】:SQL Query to compare two tables for names用于比较两个表的名称的 SQL 查询
【发布时间】:2016-05-10 23:38:49
【问题描述】:

我正在构建一个 SQL 查询,它通过 [name] 列比较两个表 A 和 B,并返回表 A 中不在表 B 中的名称

例子

Table A

ID Name Address 
1  A    ABC
2  B    XYZ
3  C    PQR

Table B
ID Name Gender 
1  A    F
2  B    M
3  D    F

我写的查询应该返回表 A 中的第三行,因为它不在表 B 中,并且应该排除所有其他行

以下是我构建的查询

Select * from A oa left join B gp ON oa.name!=gp.name

上面没有返回我期望的结果。 这可以纠正吗?

【问题讨论】:

    标签: mysql sql-server tsql


    【解决方案1】:

    最简单的方法:

    select * from A where name not in (select name from B)
    

    更好的方法:

    select * from A where not exists (select 1 from B where B.name = A.name)
    

    【讨论】:

      【解决方案2】:

      “A left join B”的意思是把所有的东西都保留在A中,如果满足条件,就关联B中的记录。

      在你的情况下,如果你真的想使用左连接,应该是这样的('=',而不是'!='):

      Select * from A oa left join B gp ON oa.name=gp.name where gp.name is null

      更好的方法是在性能方面使用“不存在”,如果空值不是问题,则使用“除外”。

      【讨论】:

        【解决方案3】:

        使用 excpet 运算符会有帮助

         select * from TableA
            except
            select * from TableB
        

        【讨论】:

          【解决方案4】:
          SELECT a.*
          FROM A a
          LEFT JOIN B b
          ON a.name = b.name
          WHERE b.name IS NULL
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-11-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-12-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多