I have a problem with building a query that would get me unique rows. The situation is:
I have a TABLE product like this:
id name price
==================
1 bolt 50
2 screw 4
3 hammer 40
4 drill 30
and a TABLE products2tags like this:
id id_product id_tag
=======================
1 1 1
2 2 1
3 2 2
4 2 3
5 3 3
In my app, I am rendering a list with all products there are and I am building a filter where a user should be able to select zero or many tags and would get a list of all products that have given tag assigned (there is a row with that product ID and tag ID in table products2tags).
A query
SELECT *
FROM products AS p
JOIN products2tags AS p2t
ON p.id = p2t.id_product
WHERE IN p2t.id_tag in (1, 3);
is working when I select only one tag in my filter (therefore there is one tag ID in the WHERE statement. When I select more tags, I still get a result, but I get some of the rows multiple times - the ones that have multiple tags assigned.
All I need is to get unique rows when selecting more than one tag.
EDIT:
Expected result of the query from the tables above:
p.id p.name p.price p2t.id p2t.id_product p2t.id_tag
==============================================================
1 bolt 50 1 1 1
2 screw 4 2 2 1 (only once)
4 drill 30 5 4 3