2013-02-12 36 views
5
獲得非匹配記錄

看到這兩個示例表:如何從兩個表

表1:

id acc_no name 
------------------------ 
1  14  aaaa 
2  16  bbbb 
3  18  ccccc 
4  25  wwww 
5  27  xxxxxxx 
6  28  zzzzzzz 

表2:

sr no acc_no amount 
---------------------- 
1  14  2000 
2  16  2344 
3  18  3200 

我需要獲得基礎記錄在表1中不匹配的acc_no:例如:

輸出:

id acc_no name 
--------------------- 
4 25  wwww 
5 27  xxxxxxx 
6 28  zzzzzzz 

當我試着用下面的查詢,結果是不可靠的:

SELECT t1.* 
FROM table1 t1 
    LEFT OUTER JOIN table2 t2 ON t1.acc_no = t2.acc_no 
WHERE t2.acc_no IS NULL 

給你的建議。什麼是正確的SQL查詢ti獲得高於輸出?

+0

爲什麼結果是不可靠? – fthiella 2013-02-12 07:49:08

+0

你的查詢是正確的。有什麼問題? – 2013-02-12 07:50:38

+0

定義可靠。 – 2013-02-12 07:52:06

回答

8

嘗試:

SELECT * 
FROM table1 t1 
WHERE t1.acc_no NOT IN (SELECT acc_no FROM table2) 
+0

乾淨,簡單..謝謝'+ 1' – 2017-05-02 16:26:10

6

應該是:

select t1.id,t1.acc_no,t1.name from table1 t1 
    left outer join table2 t2 on t1.acc_no = t2.acc_no 
     where 
    t2.id is null 
+0

@Devand Rathod:這隻適用於兩個表中的Id字段是相關的 - 例如表1 Id是表2中的外鍵。從海報的示例代碼來看,它不清楚(儘管可能),情況就是這樣。 – Anthill 2013-02-12 08:12:27

+0

你的權利,但acc_no呢?如果你使用acc_no呢? – 2013-02-12 08:16:30

+0

你可以使用acc_no,正如我所知。 – 2013-02-12 08:17:42

1

試試這個也:

select t1.* from table1 t1 where 
    not exists (
    select 1 from table2 t2 
    where t1.acc_no=t2.acc_no 
    )