The title of this thread wasn't the easiest to figure out, so it wouldn't surprise me if it's misleading.
However - I've got a MySQL table of nested set model (test_competence) containing categories where users (test_users) could pick multiple of them. The links between users and categories are located in test_list_competence.
In other words we've got three tables in total:
test_competence(id, name, lft, rgt, parent)
test_users(id, alias, occupation)
test_list_competence(user, competence)
We've also got a table named test_occupation with exactly the same structure as test_competence, but this table isn't relevant at the moment.
Now let's take some example data (not required to read/understand but could simplify):
test_competence(1, "Competences", 1, 14, 0)
test_competence(2, "Languages", 2, 9, 1)
test_competence(3, "Interpreting", 3, 8, 2)
test_competence(4, "Persian", 4, 5, 3)
test_competence(5, "Arabic", 6, 7, 3)
test_competence(6, "Crafts", 10, 13, 1)
test_competence(7, "Joinery", 11, 12, 6)
test_users(32, "Peter", 56)
test_list_competence(32, 4)
test_list_competence(32, 5)
test_list_competence(32, 7)
Now we've got a user named Peter with the categories Persian, Arabic and joinery. He appears to be a pharmacist in this example.
So, on a PHP page I'd like to present the users with their categories (in this case also called "competences"). Right now I'm doing this with the following hellish query:
SELECT u.id,
u.alias,
(SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") FROM test_occupation AS node, test_occupation AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = u.occupation AND parent.id != 1 ORDER BY parent.lft) AS occupation,
GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = l.competence AND parent.id != 1 ORDER BY parent.lft) SEPARATOR "<br />\n") AS competences
FROM test_users AS u,
test_list_competence AS l
WHERE u.id = l.user
GROUP BY u.id
ORDER BY u.alias;
And I could consequently present Peter's information like this:
Peter
Occupation: Pharmacist
Competences:
Languages » Interpreting » Persian
Languages » Interpreting » Arabic
Crafts » Joinery
But I want to present his information like this (the dots represents indent):
Peter
Occupation: Pharmacist
Competences:
...Languages
......Interpreting
.........Persian
.........Arabic
...Crafts
......Joinery
It's very easy to list only all the competences like this, so it shouldn't be too hard to do it together with the users, should it? Take a look at the following query that only lists all the competences:
SELECT node.id,
node.name,
node.parent,
(COUNT(parent.id) - 1) AS depth
FROM test_competence AS node,
test_competence AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.id
ORDER BY node.lft;
So, how do I solve this?
Thank you in advance!