I have a mysql table named “category”. the basic structure looks like this-
------ -------- ------
cat_id cat_name parent
------ -------- ------
1 test1 NULL
2 test2 NULL
3 test3 2
4 test4 1
5 test5 3
now i want all the category data with parent category name (not only id) in a single query. is that possible? i could do it by using a second query (getting child’s parent name) in a while loop and merging data as a whole. but is it possible to do this with a single query?
Join the table with itself, using the
parentcolumn to link to the cat_id of the parent.NULL), I put aLEFTso those rows are displayed as well. If you don’t wantOUTER JOIN
that, use a
JOINinstead ofLEFT OUTER JOIN.text or …) instead of the
NULLby usingCOALESCE.WHERE c2.cat_name = 'test2'