我有2个表:Products和ChildProducts。
我需要选择给定CategoryID的所有产品以及不具有相同CategoryID的相关ChildProducts
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 CategoryID = 1将返回:
Results:
A Test1
A1 Test4
A2 Test5
A3 Test6
B Test2
B1 Test7
B2 Test8
答案 0 :(得分:1)
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