title: Can this be done with single SQL query
body: <p>I'm using MySQL. I have a table</p>
  
  <pre><code>Type SubType
  1 1
  1 5
  1 6
  1 8
  2 2
  2 3
  3 1
  3 2
  3 3
  </code></pre>
  
  <p>For each type there is some number of subtypes. For every subtype in a type there is a corresponding subtype in the next type:</p>
  
  <pre><code>(1,1) =&gt; (2,2)
  (1,5) =&gt; (2,3)
  (1,6) =&gt; (2,2)
  (1,8) =&gt; (2,3)
  (2,2) =&gt; (3,1)
  (2,3) =&gt; (3,2)
  </code></pre>
  
  <p>In case you haven't seen the pattern, here it is: you sort both current and next types by subtype, then in the next type you get subtype in the same position as your current subtype in current type is. If there are more subtypes in the current type that in the next one, you warp around and start from the first subtype in the next type.</p>
  
  <p>Is it possible to construct a query that takes current type and subtype and returns corresponding subtype in the next type?</p>