Question

I'm having difficulty with the current model for my MySQL Table, namely that I can't seem to properly query all the child nodes of a specific parent. As the title states, I'm using the adjacency model.

The problem is that most methods I have found online either query all leaf nodes, or select more than just what I'm attempting to grab.

The first tutorial I was following was on MikeHillyer.com, and his solution was to the effect of:

SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;

The problem with this, is it queries all of the leaf nodes, and not just the ones related to the parents. He also suggested using the Nested Set Model, which I REALLY don't want to have to use due to it being a little more difficult to insert new nodes (I do realize it's significance though, I'd just rather not have to resort to it).

The next solution I found was on a shared slideshow on slide 53 (found from another answer here on StackOverflow). This solution is supposed to query a node's immediate children, only... The solution does not seem to be working for me.

Here's their solution:

SELECT * FROM Comments cl
LEFT JOIN Comments c2
  ON(c2.parent_id = cl.comment_id);

Now, my table is a little different, and so I adjusted some of the code for it. A brief excerpt of my table is the following:

 Table: category
 id | parent | section  | title    | ...
----+--------+----------+----------+-----
 1  |  NULL  | home     | Home     | ...
 2  |  NULL  | software | Software | ...
 3  |   2    | software | Desktop  | ...
 4  |   2    | software | Mobile   | ...
 5  |  NULL  | about    | About    | ...
 6  |   5    | about    | Legal    | ...
... |  ...   |  ...     |  ...     | ...

When I modified the above query, I did the following:

SELECT * FROM category cat1
LEFT JOIN category cat2
  ON(category.parent = cl.id);

This resulted in EVERYTHING being queried and tied in a table twice as long as the unaltered table (obviously not what I'm looking for)

I'm pretty certain I'm just doing something wrong with my query, and so I'm just hoping someone here can correct whatever my mistake is and point me in the right direction.

I know it's supposed to be easier to use a Nested Set Model, but I just dislike that option for the difficulty of adding new options.

Was it helpful?

Solution

Looks like you're very close. Your left join is guaranteeing that all records from the table will be returned.

See the below query.

SELECT c1.*, c2.id FROM category c1 INNER JOIN category c2 ON (c1.parent = c2.id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top