【问题标题】:SQL query to fetch the data from two tables with "not in" conditionSQL 查询以从具有“不在”条件的两个表中获取数据
【发布时间】:2013-06-01 06:35:16
【问题描述】:

我有 2 个表,Table1 和 Table2,两个表中的 2 列是相同的

更新:Table1.col1 的类型与 Table2.col1 相同,Table1.col2 与 Table2.col2 相同

尝试获取 table1.col1 不在 table2.col1 和 table1.col2 不在 table2.col2 中的数据,这是我的查询。

select * from Table1 
    where Table1.col1 not in (select Table2.col1 from Table2)
      and Table1.col2 not in (select Table2.col2 from Table2)

想知道更好的方法还是这样正确?

【问题讨论】:

  • 由于表格是相同的,您不需要将条件放在两列上,您只需要一个
  • @ArturUdod 它行不通……除了匹配值之外,这将为您提供笛卡尔积,也许您想说LEFT JOINWHERE col1 IS NULL
  • @Stephan 除了两列之外,这两个表都非常不同。
  • 我明白了,但是 table1 中的组合 (col1,col2) 与 table2 相同?
  • @Stephan,是的,我错了

标签: sql sql-server sql-server-2008 tsql join


【解决方案1】:

这个查询应该可以完成这项工作,我根据您的查询运行了一个简单的测试,但它没有产生预期的结果

SELECT *
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.col1 = t2.col1 AND t1.col2 = t2.col2
WHERE t2.col1 IS NULL AND t2.col2 IS NULL

鉴于此

CREATE TABLE Table1
(
colA    VarChar(50),
col1    Int,
col2    Int
)

CREATE TABLE Table2
(
colB    VarChar(50),
col1    Int,
col2    Int
)

INSERT Table1
VALUES ('A', 1, 1),
        ('B', 1, 2),
        ('C', 2, 1)

INSERT Table2
VALUES ('X', 1, 1),
        ('Y', 2, 1),
        ('Z', 2, 2)

如果我理解你的问题,我们应该得到这个B | 1 | 2

【讨论】:

  • 这取决于对期望结果的解释。并且只需要测试一个 null 就好像其中一个不匹配那么它就不会加入。
  • @Blam 是的,我说如果我正确理解了这个问题,操作员说where table1.col1 not in table2.col1 table1.col2 not in table2.col21,但他的查询没有返回任何记录集我预计,很可能我误解了这个问题。
  • 我的情况也一样,得到了结果,谢谢杰森
【解决方案2】:

使用左连接:

SELECT Table1.* 
FROM Table1 
LEFT JOIN Table2
  ON Table1.col1 = Table2.col1
  AND Table1.col2 = Table2.col2
WHERE Table2.col1 IS NULL

【讨论】:

  • 在正确的条件下使用 INNER JOIN 会不会更好? LEFT JOIN 性能不是最好的。
  • 如果你使用 '=' 那么是的,但是使用 '' 我相信 LEFT JOIN 的执行计划更简单。可能取决于 DBMS,我没有研究过。
  • @Wallack 内部连接不会识别不匹配的值。
【解决方案3】:

如果此查询有任何问题,请发表评论:

select * from table1
where not exists (select 1 from table2 where table2.col1 = table1.col1 and table2.col2 = table1.col2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多