SQL - 比较 2 个表并显示不存在的数据
SQL - Compare 2 tables and show non existent data
好的,我有 2 个表需要进行比较。这个想法是向数据库中尚未购买特定产品的任何人显示。
Table 1
UserID Customer ProductsSold
1 John Cookies
2 Susan Cake
3 Jim Bread
Table 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 匹配,只有产品名称匹配。我知道这很容易,但我现在是一片空白。
此外,对于格式不佳,我们深表歉意
杰森
使用 cross join
概括所有可能的组合并过滤掉存在的组合:
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
好的,我有 2 个表需要进行比较。这个想法是向数据库中尚未购买特定产品的任何人显示。
Table 1
UserID Customer ProductsSold
1 John Cookies
2 Susan Cake
3 Jim Bread
Table 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 匹配,只有产品名称匹配。我知道这很容易,但我现在是一片空白。
此外,对于格式不佳,我们深表歉意
杰森
使用 cross join
概括所有可能的组合并过滤掉存在的组合:
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