0

这些是我的表:

User, Product, DiscountGroup, DiscountUser, DiscountProduct.

折扣产品:

id    discountGroupId    productId     discount
---   --------------     ---------     -------
1        2                8             2000
2        3                8             1000
3        2                4              4500

折扣用户:

id    discountGroupId    userId   
---   --------------     --------- 
1        2                2        
2        3                3        
3        2                2    

折扣组:

id    title   active
---   ------ --------     
1       A      1         
2       B      0       
3       C       1    

我使用 SQL Server 2000。

我想要的是 :

首先:为每个 productid 和 member 找到他们都属于它的 discountGroup。

我写我的查询:

select * 
from discountGroup 
where id in (select discountgroupId 
             from discountproduct 
             where productid = 11)
  and id in (select discountgroupId 
             from discountuser 
             where userid = 2)
  and active = 1

第二:我想找到特殊产品和会员的最大折扣。

我该怎么做?

第三:对于特殊用户和所有产品我想找到最好的折扣和折扣组标题:

一样的:

user  produc    discount   discountGroup
---   -----     -------    ------------
ali   phone     400            A
reeza mobile     200           B 
4

1 回答 1

1

不要使用子查询,使用连接:

select g.id, p.discount
from DiscountGroup g
inner join DiscountProduct p on p.discountGroupId = g.id
inner join DiscountUser u on u.discountGroupId = g.id
where p.productid = 11 and u.userid = 2

要获得最大折扣,请使用最大聚合:

select max(p.discount)
from DiscountGroup g
inner join DiscountProduct p on p.discountGroupId = g.id
inner join DiscountUser u on u.discountGroupId = g.id
where p.productid = 11 and u.userid = 2
于 2009-08-22T09:28:51.457 回答