I am trying to construct a SQL query that returns all the rows (id’s) that have tag: 3 AND tag: 4 – in this case it is the single row for 564800
, however I can’t seem to figure out how to make this work. The image attached shows what progress I’ve made (it’s a really simple example). I am hoping to be able to generalize this statement so that I can pass it any length of tag_ids and it will filter the list to only the applicable id’s.
This is the query so far:
SELECT cars.id, array_agg(car_tags.tag_id) AS tag_ids FROM "cars" INNER JOIN "car_tags" ON "car_tags"."car_id" = "cars"."id" GROUP BY cars.id;
2
Answers
You could use:
The subquery finds all cars having both tags of id 3 and 4. This subquery is used to restrict the outer query to only cars having these two tags.
How about using
exist
? You may need to dynamically construct the where part though: