title: Fetching linked list in MySQL database
body: <p>I have a MySQL database table with this structure:</p>
  
  <pre><code>table
      id INT NOT NULL PRIMARY KEY
      data ..
      next_id INT NULL
  </code></pre>
  
  <p>I need to fetch the data in order of the linked list.  For example, given this data:</p>
  
  <pre><code> id | next_id
  ----+---------
    1 |       2
    2 |       4
    3 |       9
    4 |       3
    9 |    NULL
  </code></pre>
  
  <p>I need to fetch the rows for id=1, 2, 4, 3, 9, in that order.  How can I do this with a database query?  (I can do it on the client end.  I am curious if this can be done on the database side.  Thus, saying it's impossible is okay (given enough proof)).</p>
  
  <p>It would be nice to have a termination point as well (e.g. stop after 10 fetches, or when some condition on the row turns true) but this is not a requirement (can be done on client side).  I (hope I) do not need to check for circular references.</p>