2009-08-22 19 views
0

Dies sind meine Tabellen zu finden:SQL-Abfrage MAx Zeile in Unterabfrage

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  

Ich benutze SQL Server 2000.

Was ich will:

zuerst: für jedes productid und Mitglied finden discountGroup dass beide von ihnen zu ihm gehören.

Ich schreibe meine Frage:

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 

Zweitens: Ich maximalen Rabatt für spezielles Produkt und Mitglied finden möge.

Wie kann ich es tun?

Drittens: für spezielle Benutzer und alle Produkt Ich möchte den besten Diskont und discountGroup Titel zu finden:

Gleiche dies:

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

Antwort

1

Verwenden von Unterabfragen nicht, verwenden Joins:

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 

Um den maximalen Rabatt zu erhalten, verwenden Sie das max-Aggregat:

Verwandte Themen