Skip to content
Advertisement

MySQL category with parent_id – SELF Join

My SQL table called categories has the following structure:

I would like to know if it’s possible to JOIN the same table and present the parent_id name. I can do this by PHP code, but I would like, because of performance issues, to retrieve as SQL Query.

See example at SQLFiddle

I’ve managed to JOIN the table, but somehow the values aren’t right. For example, the result of SQLFiddle retrieves:

Which is wrong, it should be:

Advertisement

Answer

Use INNER JOIN instead of LEFT JOIN and you have to join on the id equal to the parent_id of the other table like this:

This will give you:


If you want to include those categories with no parent, use LEFT JOIN instead of INNER JOIN.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement