2012-08-27 129 views
-4

我有兩個表說說Table1(ID,Name,Description)和Table2(ID,Name,Description)。兩個表不匹配列值

我需要找出Table1中不存在的那些記錄,並且如果存在記錄,那麼它將比較它的名稱和描述並顯示哪個列不匹配。 ID是用於比較的字段。

Table 1 
(1, Jon,Student) 

Table 2 
(1,Jon, Teacher) 

所以查詢應該返回說明不匹配

+1

您是否在等待某人爲您編寫查詢,或者您是否有問題? – Candide

+0

你有沒有嘗試過任何東西?你需要SQL中的幫助? – Adil

+2

這是功課嗎?你有什麼嘗試? – devundef

回答

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 

解決這個問題。如果你只是想這是不同的加入到聯合行分別是條款

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 
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