Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL-比较两个表并显示不存在的数据_Sql_Sql Server_Sql Server 2016 - Fatal编程技术网

SQL-比较两个表并显示不存在的数据

SQL-比较两个表并显示不存在的数据,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

好的,我有两个表需要比较。这个想法是向数据库中没有购买特定产品的任何人展示

表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 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