SQL如何比较两个不同表中的两列数据?

10

我有两个表,其中表1包含4列,而表2包含8列。我想将表1中的两列与表2中的两列进行比较。

Table 1 have column1 and column2 (that needs to be compared)
Table 2 have column6 and column7 (that needs to be compared) 

我需要比较这两列的组合。我尝试了以下查询,但它没有起作用。

Select * from table1 
where column1, column2 NOT IN (Select column6, column7 from table2)

我如何比较这两个表中的两列?


你想从t1中选择所有行,其中t1.column1 <> t2.column6且t1.column2 <> t2.column7吗? - Márcio Gonzalez
1
你正在使用SQL Server和/或MySQL吗?(不要标记未使用的不同DBMS产品!) - jarlh
请提供一些示例数据以展示您需要的行为,我可以从几个不同的角度解释您的帖子。 - MatBailie
7个回答

3

Except 展示了两个表之间的差异(Oracle 开发人员使用 minus 代替 except,语法和用法相同)。它用于比较两个表之间的差异。例如,我们来看一下这两个表之间的差异。

SELECT * FROM
 table1
EXCEPT
SELECT * FROM
 table2

我使用了这种方法取得了巨大的成功。然而,我希望有一种方法可以突出显示数据不同的确切值和列?谢谢 - raddevus

2
尝试使用减法语句。这将给您来自 table1 的第一个 select 语句中不在 table2 的第二个 select 语句中的任何结果。
select column1, column2 from table1
minus
select column6, column7 from table2

2

NOT EXISTSNOT IN的“null safe”版本。 如果你想表达的是table2中column1和column2不在同一行的组合:

select *
from table1
where NOT EXISTS (select 1 from table2
                  where table1.column1 = table2.column6
                    and table1.column2 = table2.column7)

如果您的意思是仅仅指table2中的column1和column2值不能来自不同的行,那么可以这样实现:

select *
from table1
where NOT EXISTS (select 1 from table2
                  where table1.column1 = table2.column6)
  and NOT EXISTS (select 1 from table2
                  where table1.column2 = table2.column7)

0

我能想到的最少比较查询是

Select t1.* 
from table1 t1
left join table2 t2 on t1.column1 in (t2.column6, t2.column7)
                    or t1.column2 in (t2.column6, t2.column7)
where t2.column6 is null

0
请尝试执行此查询:
 Select 
     case when (table1.column1 = table2.column6) 
         then 1 else 0 
     end column1_6 check, 
     case when (table1.column2 = table2.column7) 
         then 1 else 0 
     end
 from 
     table1 
 inner join
     table2 on table1.ID = Table2.ID

0
SELECT *  FROM table1 t1
RIGHT JOIN table2 t2
WHERE
t1.c1 = t2.c6 AND
t1.c2 = t2.c7

2
尽管这可能回答了问题,你可能想提供一些额外的细节并解释答案。以其当前状态,该答案质量较低。 - Rolf ツ

-1
    select * from table1 where column1 not in(select column 6 from table2) or column2 not in(select column7 from table2)

这将从table1中返回行,其中col1和col6或col2和col7之间存在差异

希望能对您有所帮助


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接