2013-11-01 141 views
0

我有2個表格:Products和ChildProducts。在sqlite中選擇所有產品和類別產品

,我需要選擇所有產品對給定類別ID及相關ChildProducts不具有相同類別ID

Products: 
ItemID CategoryID Name 
A   1   Test1 
B   1   Test2 
C   2   Test3 
A1  0   Test4 
A2  0   Test5 
A3  0   Test6 
B1  0   Test7 
B2  0   Test8 
C1  0   Test9 
C2  0   Test10 
C3  0   Test11 
C4  0   Test12 

Child Products: 
ParentItemID ChildItemID 
A      A1 
A      A2 
A      A3 
B      B1 
B      B2 
C      C1 
C      C2 
C      C3 
C      C4 

所以需要的所有產品,其parentItemID是在給定的類別,IE類別id = 1將返回:

Results: 
A   Test1 
A1   Test4 
A2   Test5 
A3   Test6 
B   Test2 
B1   Test7 
B2   Test8 

回答

1

SQLFiddle demo

select p1.ItemID 

from Products p1 
LEFT JOIN ChildProducts cp on p1.ItemId=cp.ChildItemID 
LEFT JOIN Products p2 on cp.ParentItemID=p2.ItemId 


    where p1.CategoryId=1 
     or 
     p2.CategoryId=1 
ORDER BY COALESCE(p2.ItemID,p1.ItemID),p2.ItemId