編輯:
我有一個帶有列的表“TableA”product, feature1, feature2
我有另一個帶有列的表“TableB”'saleorder, feature1, feature2'
目前我使用內連接來顯示具有匹配列值的產品
SELECT distinct a.product
FROM TableA a
INNER JOIN TableB b
ON a.feature1 = b.feature1
AND a.feature2 = b.feature2
目前,這向我展示了 TableA 中與 TableB 中的 feature1、feature2 完全匹配的產品。
我想修改它,以便我看到 TableA 中那些與 feature1、feature2 不匹配的產品。在某種程度上與原始腳本的輸出相反,僅顯示那些不存在具有特征 1 和特征 2 的銷售訂單的產品。
如何使用 T-SQL 執行此操作?
uj5u.com熱心網友回復:
from TableA which did not match for feature1 and feature2, but matched for feature3:
SELECT distinct a.feature3, a.feature1, a.feature2, b.feature1, b.feature2
FROM TableA a
INNER JOIN TableB b
ON a.feature3 = b.feature3
AND a.feature1 <> b.feature1
AND a.feature2 <> b.feature2
uj5u.com熱心網友回復:
第 1 步:從 TableA 中獲取所有具有 NULL 的來自 TableB 的特征 1 和特征 2 的行,這些行對于沒有來自 TableA 的“特征1”和“特征2”的對應匹配值的行。
SELECT A.product,
A.feature1 Afeature1,
A.feature2 Afeature2,
B.feature1 Bfeature1,
B.feature2 Bfeature2
FROM tablea A
LEFT OUTER JOIN tableb B
ON A.feature1 = B.feature1
AND A.feature2 = B.feature2;
--- 這將有這樣的輸出
product Afeature1 Afeature2 Bfeature1 Bfeature2
abcd l l m m
efgh x y NULL NULL -----> this is what you want.
第 2 步:所以現在您只需要過濾掉在早期輸出中??獲得的 TableB 中列的 NOT NULL 值。
SELECT productA,Afeature1,Afeature2
FROM (SELECT A.product productA,
A.feature1 Afeature1,
A.feature2 Afeature2,
B.feature1 Bfeature1,
B.feature2 Bfeature2
FROM tablea A
LEFT OUTER JOIN tableb B
ON A.feature1 = B.feature1
AND A.feature2 = B.feature2)
WHERE bfeature1 IS NULL
AND bfeature2 IS NULL;
最終輸出:
product Afeature1 Afeature2
efgh x y
uj5u.com熱心網友回復:
NOT EXISTS如果不需要 TableB 中的列,則可以使用 a
SELECT DISTINCT product
FROM TableA p
WHERE NOT EXISTS
(
SELECT 1
FROM TableB s
WHERE s.feature1 = p.feature1
AND s.feature2 = p.feature2
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367504.html
