[英]SQL - Compare 2 tables and show non existent data
好的,我有 2 個表需要進行比較。 這個想法是顯示數據庫中沒有購買特定產品的任何人。
表格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 匹配,只有產品名稱匹配。 我知道這很容易,但我現在正在畫一個空白。
另外,很抱歉格式不佳
傑森
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.