2

I have a problem in getting records in 1 to many relationship. following is the scenario,

table products
---------------------
id | name
---------------------
1 | product1
2 | product2
3 | product3
4 | product4


Categories
-------------
id | name
-------------
1 | A
2 | B
3 | C


product_categories
-------------------
pid | cid
-------------------
1 | 1
1 | 2
1 | 3
2 | 2
2 | 3
3 | 2
3 | 3
4 | 3

I want to select products based on category name.

if my condition is category B and C then the expected output would be,

Expected Result:

----------------------------
Product_name |  category_name
----------------------------
Product2 | B
Product2 | c
Product3 | B
Product3 | c

if my category is C then only product4 should be shown.

Please help me in this.. I have tried so many ways and techniques like IN, NOT IN, exists and not exists along with possible join operations but nothing worked.

4

2 に答える 2

4

IN句で指定されたパラメータの数に等しいレコードのインスタンスの数をカウントする必要があります。

SELECT  a.Name
FROM    products a
        INNER JOIN product_categories b
            on a.id = b.pid
        INNER JOIN Categories c
            on b.cid = c.id
WHERE   c.name IN ('B','C')
GROUP BY a.NAME
HAVING COUNT(*) = 2
于 2012-09-19T16:06:19.530 に答える
-1
SELECT * FROM products p
INNER JOIN product_categories pc ON p.id = pc.pid
INNER JOIN Categories c ON pc.cid = c.id
WHERE c.name IN('B', 'C');
于 2012-09-19T16:20:47.683 に答える