我有3张表,如下所示:
[Products table] 1 -> many [Ratings table] many < - 1 [Customers table]
每个客户可以对每个产品评分一次,我可以有1个产品已被多个客户评级(即很多)
我的问题是:如何让查询仅列出特定客户尚未评级的产品?
我尝试过:
create procedure GetRatings
(
@CustomerID int
)
as
begin
select p.ID,p.Name...
from products p join ratings r
on p.productID = r.ProductID
where r.CustomerID != @CustomerID
但是,这并没有推出其他客户评价的相同产品。所以现在,如果我得到一台惠普550笔记本电脑,它被不同的客户评为两次, 此查询将仅启动@CustomerID评级的评级,而不是第二个评级。任何人都可以帮我这个吗?
答案 0 :(得分:3)
所有未被@customer评级的产品:
select
p.ID,
p.Name
from
products p
where
p.ID not in
(select distinct ratings.productID from ratings
where ratings.customerID = @CustomerID)
@customer未评级的产品的所有评级:
select
p.ID,
p.Name,
r.*
from
products p
inner join
ratings r on p.productID = r.ProductID
where
p.ID not in
(select distinct ratings.productID from ratings
where ratings.customerID = @CustomerID)
答案 1 :(得分:0)
类似的东西:
select p.*
from products p
where not exists (
select 1
from ratings r
where r.customerid = ?
and r.productid = p.productid
)
如果您想以加入方式表达:
select p.*
from products p
left join ratings r
on r.customerid = ?
and r.productid = p.productid
where r.productid is null