Reputation: 167
PRODUCTID;NAME
1 ;BMW
2 ;AUDI
3 ;Mercedes
4 ;Volvo
CATID;CATNAME
1 ;Car
2 ;Motorcicle;
3 ;Bus
PRODUCTID;CATID;
1 ;1
1 ;2
2 ;1
3 ;1
4 ;3
if I use SQL
SELECT productID FROM productCategiresRel WHERE catID IN (1,2)
the result is
productCategiresRel
PRODUCTID;CATID;
1 ;1
1 ;2
2 ;1
3 ;1
4 ;3
but I want the to select these products which is represented in both select categories (Car and Motorcicle).
The result should be:
PRODUCTID;CATID;
1 ;1 (Car)
1 ;2 (Motorcicle)
Upvotes: 0
Views: 172
Reputation: 727
Or if you want to find all products that are in multiple categories--not just in Categories 1 and 2-- try this:
SELECT *
FROM products
WHERE productID IN (
SELECT productID
FROM productCategiresRel
GROUP BY productID
HAVING COUNT(*) > 1
);
Upvotes: 0
Reputation: 3963
You can use an EXISTS
to check multiple times.
SELECT *
FROM products
WHERE EXISTS (SELECT ''
FROM productCategiresRel
WHERE catID = 1
AND productCategiresRel.productId = products.productId)
AND EXISTS (SELECT ''
FROM productCategiresRel
WHERE catID = 2
AND productCategiresRel.productId = products.productId)
Upvotes: 2