sql - 显示未包含在特定价目表中的产品?
问题描述
我有以下 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”中的产品不会显示。但它应该只显示那些不在价目表“星期五栏”中的产品。
任何帮助,将不胜感激!
解决方案
是的,如果您加入,当它存在于其他价目表中时,您不能将其排除,因为您将获得每个价目表的一行。相反,您必须专门检查该价目表中的价格是否存在,例如
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'
)
推荐阅读
- git - Visual Studio Code、Windows、Git 客户端(版本 2.20.1)无法将代码推送到 GitHub 503 错误
- php - Send Push notification with Flutter + OneSignal for PlayerID
- ruby-on-rails - collect_select,我只想在下拉菜单中选择管理员角色为 true 的用户
- arrays - 推送函数似乎正在覆盖 Angular 中的每个数组元素
- c# - ASP.NET 用户不会出现在 SSMS 中
- java - 无法使用 SAX 解析器捕获元素
- linux - 双引号bash脚本linux
- python-3.x - 如何将多个单元格添加到bigtable表格中的一行?
- regex - 在 Notepad++ 中使用正则表达式在第二个冒号后擦除
- ssas - SSAS Cubes 在本地机器上处理,但不在服务器上