SQL-запрос для поиска строки MAx в подзапросе - PullRequest
0 голосов
/ 22 августа 2009

Это мои таблицы:

User, Product, DiscountGroup, DiscountUser, DiscountProduct.

DiscountProduct:

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

DiscountUser:

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

DiscountGroup:

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

Я использую SQL Server 2000.

Что я хочу:

сначала: для каждого продукта и члена найдите 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 

1 Ответ

1 голос
/ 22 августа 2009

Не используйте подзапросы, используйте объединения:

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
...