Hope the title is not that confusing – honestly said I had no idea how to better explain my problem in a single line 🙂 (and Google it properly BTW)
A table ‘group’ is structured as a nested set to create tree menues. Articles in a table ‘article’ reference to ID of such group element to – well – group them:
Table 'article' Table 'group'
id | article | groupid id | title | left | right
1 | Bowl | 2 1 | material | 1 | 6
2 | Bowl | 5 2 | wood | 2 | 3
3 | Cube | 3 3 | steel | 4 | 5
4 | Cube | 6 4 | shape | 6 | 13
5 | Bowl | 10 5 | circle | 7 | 8
6 | Pyramid | 2 6 | square | 9 | 10
7 | Pyramid | 3 7 | rectangle| 11 | 12
8 | Pyramid | 11 8 | color | 14 | 21
9 | Bowl | 11 9 | red | 15 | 16
10 | Cube | 9 10 | green | 17 | 18
11 | Pyramid | 9 11 | blue | 19 | 20
To select any combination of group elements, I simply have a query mentioning a range from group.left to group.right, giving me a set of group.id that I can compare with article.groupid.
Following statement responds all articles consisting of wood:
SELECT
a.article
FROM
article AS a
LEFT JOIN
group AS g
ON (
(
2 >= g.left
AND
3 <= g.right
AND
g.id = a.groupid
)
)
GROUP BY
a.article
Now my question: how should I create a query, that responds with e.g. all articles that consist of wood AND have ANY color?
I expected that repeating concatenated subqueries in the WHERE clause would make the deal:
SELECT
a.article
FROM
article AS a
WHERE
a.groupid IN
(
SELECT
CONCAT(g.id) AS gr
FROM
group AS g
WHERE
(
2 >= g.left
AND
3 <= g.right
)
)
AND
a.groupid IN
(
SELECT
CONCAT(g.id) AS gr
FROM
group AS g
WHERE
(
14 >= g.left
AND
21 <= g.right
)
)
This query responds no result. BTW I dont like subqueries but many efforts with JOINS and Sub-JOINS did not work as well.
My mind is spinning – any tips from you guys?
Thanks
edited: now working. Test it here (but in MSSQL)
First approach based on your query, problem comes from non well normalized design. To do the query you will to check if exists a row on articles with same name that references a kind of property:
Edited
OP uses nested sets. But perhaps article’s table is still not well normalized. I suggest to take in consideration this design:
sample normalized data: