I have a table of properties:
+----+-----------------------------+
| prop_id | prop_name |
+---------+------------------------+
| 1 | Cottage |
+---------+------------------------+
| 2 | Mountain House |
+---------+------------------------+
| 3 | Beach house |
+---------+------------------------+
A table of accessories:
+----+-----------------------------+
| acc_id | acc_name |
+---------+------------------------+
| GAR | With garden |
+---------+------------------------+
| TER | With terrace |
+---------+------------------------+
| REN | Recently renovated |
+---------+------------------------+
A table that relates properties and accessories (properties2accessories):
+----+--------------+
| prop_id | acc_id |
+---------+---------+
| 1 | GAR |
+---------+---------+
| 1 | REN |
+---------+---------+
| 2 | GAR |
+---------+---------+
| 2 | REN |
+---------+---------+
| 2 | TER |
+---------+---------+
| 3 | GAR |
+---------+---------+
| 3 | TER |
+---------+---------+
I need all the properties that have ALL the accessories that I pass as parameters.
Correct examples:
a) Properties with "Garden" and "Recently renovated":
I should get props: 1, 2
b) Properties with "Garden" and "Terrace":
I should get props: 2, 3
I try:
SELECT *
FROM properties2accessories
WHERE acc_id IN ('GAR', 'REN');
but this get prop 3 too, that not has "Recently renovated"
I’m using Postgres 13
Any helps?
3
Answers
You con check with exists if another condition is present for a specific id
fiddle
You could do something like this:
That’s what HAVING can do for you, it’s a WHERE condition over the entire group: