我使用SQL Server 2008數據庫。如何從表A中查找不存在於表B中的記錄?
我有兩個表的列這樣的:
Table A
:
request_id|order_id|e-mail
100 |2567 |[email protected]
100 |4784 |[email protected]
450 |2578 |[email protected]
450 |8432 |[email protected]
600 |9032 |[email protected]
600 |9033 |[email protected]
Table B
也已經id
和order_no
列和許多其他列:
Table B
:
request_id|order_id|e-mail
100 |2563 |[email protected]
300 |4784 |[email protected]
600 |9032 |[email protected]
650 |2578 |[email protected]
850 |8432 |[email protected]
正如你所看到的,在表A中給定的request_id
可以出現不止一次(見100 & 450條記錄)
我需要找到從表格中的所有記錄,它通過order_id
不存在於表B,但有相同的request_id
列值。
對於上面的例子,我希望這樣的事情:
Output
:
request_id|order_id|e-mail
100 |2567 |[email protected]
100 |4784 |[email protected]
450 |2578 |[email protected]
450 |8432 |[email protected]
600 |9033 |[email protected]
正如你可以看到從上面的表格中的記錄不存在於表B.此標準是僅僅滿足於記錄下order_id=600
我創建了T-SQL查詢的草圖:
select
D.request_id, D.order_id
from
table A AS D
where
D.request_id = 600
and D.order_id not in (select M.order_id
from table B AS M
where M.request_id = 600)
不幸的是,我不知道如何轉換我的查詢所有request_id
。第一個想法是使用while循環遍歷表A中的所有request_id
,但在SQL世界中似乎並不聰明。
感謝您的幫助
謝謝。目前我無法用真實的例子來測試它,但它似乎起作用!一個問題:我是否將最後一個WHERE條件更改爲「WHERE b.order_id IS NULL」?我發現它也可以工作,對我來說似乎更舒服,因爲我想查找所有不匹配的request_id :) – Viper
因爲在JOIN子句中使用了兩個列('request_id'和'order_id')你不需要它。這是同一件事。 – AgentSQL
也許我錯誤理解了這個要求,但我認爲OP在說他希望所有在表B中有與request_id上的表A匹配的記錄但不是order_id上的記錄的情況。上面的查詢將列出來自表A的記錄,這些記錄在request_id或order_id上的表B中沒有匹配。 – Jay