title: How to fetch categories and sub-categories in a single query in sql? (mysql)
body: <p>I would like to know if it's possible to extract the categories and sub-categories in a single DB fetch.</p>
  
  <p>My DB table is something similar to that shown below</p>
  
  <p>table</p>
  
  <pre><code>cat_id parent_id
  1      0
  2      1
  3      2
  4      3
  5      3
  6      1
  </code></pre>
  
  <p>i.e. when the input is 3, then all the rows with parent_id as 3 AND the row 3 itself AND all the parents of row 3 should be fetched.</p>
  
  <p>output</p>
  
  <pre><code>cat_id parent_id
  3      2   -&gt; The row 3 itself
  4      3   -&gt; Row with parent as 3
  5      3   -&gt; Row with parent as 3
  2      1   -&gt; 2 is the parent of row 3
  1      0   -&gt; 1 is the parent of row 2
  </code></pre>
  
  <p>Can this be done using stored procedures and loops? If so, will it be a single DB fetch or multiple? Or are there any other better methods?</p>
  
  <p>Thanks!!! </p>