首页 > 解决方案 > 显示未包含在特定价目表中的产品?

问题描述

我有以下 4 个表:

create table Productgroup
(
    productgroup_id char(4) primary key,
    productgroupName varchar(25) not null
)

create table Product
(
    product_id char(4) primary key,
    productName varchar(25) not null,
    product_productgroup_id char(4) 
        constraint product_productgroup_id_foreign 
            foreign key references Productgroup(productgroup_id)
)

create table Pricelist
(
    pricelist_id char(4) primary key,
    pricelistName varchar(25) not null
)

create table Productprice
(
    productprice_id int identity(1000, 1) primary key,
    price int not null,
    discount decimal(10,2),
    product_productprice_id char(4) 
         constraint product_productprice_id_foreign 
             foreign key references Product(product_id),
    pricelist_productprice_id char(4) 
         constraint pricelist_productprice_id_foreign 
             foreign key references Pricelist(pricelist_id)
)

每个产品都有一个产品组,并且可以包含在具有不同价格的不同价目表中。

到目前为止,我有 2 个价目表,一个名为“商店”的价目表和一个名为“星期五酒吧”的价目表。我想进行查询以显示产品未包含在价目表“星期五酒吧”中的产品和产品组。

到目前为止,我有这个代码:

SELECT 
    Productgroup.productgroupName, Product.productName 
FROM 
    Product
JOIN 
    Productgroup ON Product.product_productgroup_id = Productgroup.productgroup_id
JOIN 
    Productprice ON Product.product_id = Productprice.product_productprice_id
JOIN 
    Pricelist ON Productprice.pricelist_productprice_id = Pricelist.pricelist_id
WHERE 
    Pricelist.pricelistName != 'Friday bar'

但这个查询的问题在于它既显示了周五柱中包含的产品,也显示了周五柱中未包含的产品。但是,仅在价目表“Friday Bar”中的产品不会显示。但它应该只显示那些不在价目表“星期五栏”中的产品。

任何帮助,将不胜感激!

标签: sqlsql-server

解决方案


是的,如果您加入,当它存在于其他价目表中时,您不能将其排除,因为您将获得每个价目表的一行。相反,您必须专门检查该价目表中的价格是否存在,例如

SELECT PG.productgroupName, P.productName
FROM Product P
INNER JOIN Productgroup PG ON P.product_productgroup_id = PG.productgroup_id
where not exists (
  select 1
  from Productprice PP
  inner join Pricelist PL ON PP.pricelist_productprice_id = PL.pricelist_id
  where P.product_id = PP.product_productprice_id
  and PL.pricelistName = 'Friday bar'
)

推荐阅读