我正在尝试编写查询来查找在另一个表中没有匹配记录的记录.
例如,我有两个表,其结构如下所示:
Table1 State | Product | Distributor | other fields CA | P1 | A | xxxx OR | P1 | A | xxxx OR | P1 | B | xxxx OR | P1 | X | xxxx WA | P1 | X | xxxx VA | P2 | A | xxxx Table2 State | Product | Version | other fields CA | P1 | 1.0 | xxxx OR | P1 | 1.5 | xxxx WA | P1 | 1.0 | xxxx VA | P2 | 1.2 | xxxx
(州/产品/分销商共同构成表1的关键.州/产品是表2的关键)
我想找到所有未使用经销商X的州/产品/版本组合.(因此本例中的结果是CA-P1-1.0和VA-P2-1.2.)
有关查询的任何建议吗?
SELECT * FROM Table2 T2 WHERE NOT EXISTS (SELECT * FROM Table1 T1 WHERE T1.State = T2.State AND T1.Product = T2.Product AND T1.Distributor = 'X')
这应该符合ANSI标准.
在T-SQL中:
SELECT DISTINCT Table2.State, Table2.Product, Table2.Version FROM Table2 LEFT JOIN Table1 ON Table1.State = Table2.State AND Table1.Product = Table2.Product AND Table1.Distributor = 'X' WHERE Table1.Distributor IS NULL
不需要子查询.
编辑:正如评论所示,DISTINCT不是必需的.谢谢!