识别不销售产品的商店

identify stores not selling a product

我有 2 个表 city_products 包含城市中的所有产品,product_list 包含不同城市中存在的所有产品 cities.I 想要每个城市中不可用的产品列表城市。

[![在此处输入图片描述][1]][1]

Table 1: city_prd

city    product
------  -------
city 1  p1
city 1  p3
city 1  p2
city 2  p1
city 2  p5

Table 2: pdt_list

product
-------
p1
p2
p3
p4
p5

期望的输出:

city    product
------  -------
city 1  p4
city 1  p5
city 2  p2
city 2  p3
city 2  p4

我知道它与交叉连接有关,但我没有得到确切的答案

你没有提到你使用的是哪个数据库,所以我会给你一个通用的 SQL 解决方案。您可以根据您的特定 RDBMS 对其进行调整。

select
  c.city, p.product
from (
  select distinct city from city_prd
) c
cross join pdt_list p
except
select city, product from city_prd
order by c.city, p.product

这是 TheImpaler 答案的变体,但它应该适用于所有数据库。使用 cross join 生成城市和产品的所有组合。然后使用 left join (或类似的机制)删除存在的那些:

select c.city, p.product
from (select distinct city from city_prd) c cross join
     pdt_list p left join
     city_prd cp
     on c.city = cp.city and p.product = cp.product
where cp.city is null;

我还猜测您有某种 cities table。您可以改用它:

select c.city, p.product
from cities c cross join
     pdt_list p left join
     city_prd cp
     on c.city = cp.city and p.product = cp.product
where cp.city is null;