I'm facing a design problematic, I have three tables:
var_storage:
id | var_name | var_value | user
post:
id | user
post_var_storage:
post_id | var_storage_id
Basically a post ManyToMany var_storage. var_storage contains var values, we can have datas like
var_storage(,MEAL,DINNER,)
var_storage(,FOOD,FRIES,)
etc ...
When a user creates a post we snapshot all its var_storage, that's why there is a many to many. ( And not post OneToMany var_storage, because other entities snapshots var_storage the same way ).
Then, our need is to query the database to find all the posts that have been created with some variables specific values.
Exemples:
"Find all rows from post created with MEAL=DINNER"
"Find all rows from post created with MEAL=DINNER AND FOOD=FRIES"
etc ...
The filtering is done on the user-side on multiple possible vars, so we cannot predict how much variables the user will want to filter on.
I setup a query pattern to see what it will look like and I want to know if there is an easier way to achieve it. Because in this one there is as much EXISTS clauses as filtered vars ( it possible to filter with 15 variables !! ), and the nested sub queries are really massive with multiple JOINs etc ..
Particularly because one of those is always the same ( the one is the FROM clause ).
SELECT * FROM
post p
WHERE
# MEAL=DINNER
EXISTS (
SELECT * FROM (
SELECT *
FROM post p2
INNER JOIN post_var_storage pvs ON pvs.post_id = p2.id
INNER JOIN vars_storage vs ON pvs.var_storage_id = vs.id
WHERE p2.id = p.id
) vs
WHERE
vs.var_name = "MEAL" AND vs.value = "DINNER"
) AND
# FOOD=FRIES
EXISTS (
SELECT * FROM (
SELECT *
FROM post p2
INNER JOIN post_var_storage pvs ON pvs.post_id = p2.id
INNER JOIN vars_storage vs ON pvs.var_storage_id = vs.id
WHERE p2.id = p.id
) vs
WHERE
vs.var_name = "FOOD" AND vs.value = "FRIES"
) AND
....