SQL-比较两个表并显示不存在的数据
好的,我有两个表需要比较。这个想法是向数据库中没有购买特定产品的任何人展示 表1SQL-比较两个表并显示不存在的数据,sql,sql-server,sql-server-2016,Sql,Sql Server,Sql Server 2016,好的,我有两个表需要比较。这个想法是向数据库中没有购买特定产品的任何人展示 表1 UserID Customer ProductsSold 1 John Cookies 2 Susan Cake 3 Jim Bread 表2 ProductCode ProductDesc Cookies 1 doz Cookies Cake 8-in cake Bread Loaf of bread 我想回来的是 1 John Cake 1 John Bread 2 S
UserID Customer ProductsSold
1 John Cookies
2 Susan Cake
3 Jim Bread
表2
ProductCode ProductDesc
Cookies 1 doz Cookies
Cake 8-in cake
Bread Loaf of bread
我想回来的是
1 John Cake
1 John Bread
2 Susan Cookies
2 Susan Bread
3 Jim Cookies
3 Jim Cake
因此,我一直在努力找出代码,因为表之间没有ID匹配,只有产品名称匹配。我知道这很容易,但我现在一片空白
另外,很抱歉格式不好
Jayson使用
交叉连接概述所有可能的组合
,并过滤掉存在的组合:
select n.id, n.name, t2.productcode
from (select distinct id, name from table1) n cross join
table2 t2 left join
table1 t1
on t1.id = n.id and t2.productcode = t1.productsold
where t1.id is null;
逻辑与Gordon相同,但应用集合运算:
select t1.UserID, t1.Customer, t2.ProductDesc
from table1 as t1 -- all possible User/Product combinations
cross join table2 as t2
except
select UserID, Customer, ProductsSold -- existing data
from table1