Reputation: 664
I have a little problem with my SQL sentence. I have a table with a product_id and a flag_id, now I want to get the product_id which matches all the flags specified. I know you have to inner join it self, to match more than one, but I don't know the exact SQL for it.
Table for flags
product_id | flag_id
1 1
1 51
1 23
2 1
2 51
3 1
I would like to get all products which have flag_id 1, 51 and 23.
Upvotes: 1
Views: 54
Reputation: 1
Try:
SELECT *
FROM TABLE_NAME A INNER JOIN TABLE_NAME B ON A.product_id = B.product_id
Upvotes: 0
Reputation: 79979
get the product_id which matches all the flags specified
This problem is called Relational Division. One way to solve it, is to do this:
GROUP BY product_id
.IN
predicate to specify which flags to match.HAVING
clause to ensure the flags each product have, like this:
SELECT product_id
FROM flags
WHERE flag_id IN(1, 51, 23)
GROUP BY product_id
HAVING COUNT(DISTINCT flag_id) = 3
The HAVING
clause will ensure that the selected product_id
must have both the three flags, if it has only one or two of them it will be eliminated.
See it in action here:
This will give you only:
| PRODUCT_ID |
--------------
| 1 |
Upvotes: 5
Reputation: 16615
Firstly it would help if you can specify what you have tried before, but as I understood you need to get products with certain flags, so you can just use WHERE
:
SELECT product_id FROM Product WHERE flag_id IN (1,2,3,4,5)
Upvotes: 0