-4

我有两个表说 Table1(ID,Name,Description)和 Table2(ID,Name,Description)。

我需要从 Table1 中找出 Table2 中不存在的那些记录,如果记录存在,那么它会比较其名称和描述并显示哪一列不匹配。ID 是用于比较的字段。

例如

Table 1
( 1, Jon,Student) 

Table 2 
(1,Jon, Teacher) 

所以查询应该返回描述不匹配

4

2 回答 2

0

你在寻找这样的东西吗?

SELECT
t1.id,
CASE
WHEN t2.id IS NULL THEN 'does not exist in table2'
WHEN t1.Name != t2.Name AND t1.Description = t2.Description THEN 'Name is different'
WHEN t1.Name = t2.Name AND t1.Description != t2.Description THEN 'Description is different'
ELSE 'Both Name and Description differ'
END AS what_is_the_difference
FROM
table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
于 2012-08-27T18:13:11.413 回答
0

您可以使用 SELECT 解决它

SELECT  TABLE1.ID,  CASE WHEN TABLE1.NAME <> TABLE2.NAME THEN 'NAME different' 
                         ELSE 'NAME equal'
                    END
                  , TABLE1.NAME, TABLE2.NAME
                  , CASE WHEN TABLE1.DESCRIPTION <> TABLE2.DESCRIPTION THEN 'DESCRIPTION different' 
                         ELSE 'DESCRIPTION equal'
                    END
                  , TABLE1.DESCRIPTION, TABLE2.DESCRIPTION
  FROM  TABLE1, TABLE2
 WHERE   TABLE1.ID = TABLE2.ID  

如果您只想要不同的联合行添加到 were 子句

AND (TABLE1.NAME <> TABLE2.NAME OR TABLE1.DESCRIPTION <> TABLE2.DESCRIPTION)

如果其他表中可能没有 ID,则必须使用左连接

SELECT      TABLE1.ID,  
            CASE WHEN TABLE2.ID IS NULL THEN 'No corresponding row in TABLE2' END
            CASE WHEN TABLE1.NAME <> TABLE2.NAME THEN 'NAME different' ELSE 'NAME equal' END,           
            TABLE1.NAME, TABLE2.NAME
            CASE WHEN TABLE1.DESCRIPTION <> TABLE2.DESCRIPTION THEN 'DESCRIPTION different' ELSE 'DESCRIPTION equal' END,
            TABLE1.DESCRIPTION, TABLE2.DESCRIPTION
       FROM TABLE1
  LEFT JOIN TABLE2 ON TABLE1.ID = TABLE2.ID  
于 2012-08-27T18:06:51.127 回答