title: MYSQL: select parent sorted alphabetically grouped with children sorted alphabetically
body: <p>I've made a simple table to understand parent-child relationship, but I don't seem to get proper results. I want to sort it </p>
  
  <ol>
  <li>first alphabetically by 'name' field, only those who have no parent (parent_id==0)</li>
  <li>BUT, whenever there are child rows for the parent, they should be printed after the parent, also sorted alphabetically by name.</li>
  </ol>
  
  <p>Example table:</p>
  
  <p>============================================================</p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS `test` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `parent_id` int(11) NOT NULL DEFAULT '0',
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
  
  --
  -- Dumping data for table `test`
  --
  
  INSERT INTO `test` (`id`, `parent_id`, `name`) VALUES
  (1, 4, 'Zorg'),
  (2, 0, 'Woordolack'),
  (3, 4, 'Akriller'),
  (4, 0, 'Metabrusher'),
  (5, 2, 'Intersplitter'),
  (6, 0, 'Beaverbrain'),
  (7, 4, 'Torgeoruos'),
  (8, 2, 'Deptezaurus');
  </code></pre>
  
  <p>============================================================</p>
  
  <h1>Here is what I want to output to a web browser using PHP:</h1>
  
  <pre><code> Beaverbrain
   Metabrusher
   -&gt; Akriller
   -&gt; Torgeoruos
   -&gt; Zorg
   Woordolack
   -&gt; Deptezaurus
   -&gt; Intersplitter
  </code></pre>
  
  <p>============================================================</p>
  
  <p>I should say that this is a sample table just to show the idea, so it can be modified in any way to get the proper result.</p>