I have a database table, where I have single table to manage all root level and their related sub categories.
Below is the table and data structure of the same, My SQL table:
id label pid
1 Parent 1 0
2 Parent 2 0
2 Parent 2 0
3 Child 1.1 1
4 Child 1.2 2
5 Child 2.1 2
6 Child 1.1.1 3
7 Child 1.1.2 3
Now, I want a single query, that gives me result, where first records are my root level category labels where pid is 0 and then below that its subcategory, whose pid is 1 and pid as label, instead of id to display in my dropdown on add page
Hope you guys understand what I am trying to say here !
Looking forward for your quick response.
Edit from comments
Tried so far, but without success, as it produces a single level of results.
SELECT p.Name, s.Name FROM Categories s LEFT JOIN Categories p ON s.mainCat = p.ID ORDER BY p.Name, s.Name;
The short version was that you seem to be trying to do a hierarchical tree, and whilst I have tried various methods out on this the one desribed on the following link seems the most efficient in the long run even though it takes a bit more work to set up in the first place.
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
For more details I’d advise reading the above article, and possibly this question which covers a similar problem.
Create a multiselect drop down with parent-child menu items
(Direct link to the answer I gave there, says pretty much the same but with a lot more explanation/rationale)
https://stackoverflow.com/a/9377018/1213554
At present your key problem is that there is no clear linking field that tells you which child links to which parent. Ideally this should be done either using the tree method detailed above, or at the most basic by having a
parentIDfield which can be either 0 (root element) or equating to the PRIMARY KEYidcolumn. This in turn allows you to more easily determine what each childs parent is.