title: SQL query to get neighbours from table with two dimensional data
body: <p>I have a table, that contains partitioning of world map. Partition is done by splitting all area into rectangles, called 'tile'. As usual, rectangle has bottom-left and upper-right corners, both referred by floating point coordinates.</p>
  
  <p>The task is this:</p>
  
  <p>For each tile get its neighbour to the right and its neighbour to the top, like a set of <code>{tile_id, id_of_top_neighbour, id_of_right_n}</code>.</p>
  
  <p>By right neighbour of tile A meant such tile B, that has the closest min_x coordinate to A's max_x coord, while y are the same. </p>
  
  <p>Description of the table:</p>
  
  <pre><code>integer tile_id; --Tile id. PK.
  real    min_x;  --X coordinate of bottom-left point
  real    min_y;  --Y coordinate of bottom-left point
  real    max_x;  --X coordinate of upper-right point
  real    max_y;  --Y coordinate of upper-right point
  </code></pre>
  
  <p>Failed solution:</p>
  
  <p>First, I tried to sort by one coordinate, iterate by this result set on the java side and then perform an additional select for each row. The performance was inadequate.</p>
  
  <p>Now I wonder if a pure SQL solution would be possible and quicker at runtime...</p>
  
  <p>Appreciated any help or ideas beforehand.</p>
  
  <p><strong>EDIT:</strong>
  There could be a gap between two tiles, so (e.g. for right neighbour) B.min_x - A.max_x could be > 0. Hovewer, two tiles cannot intersect more, than by boundary.</p>
  
  <p>We are using Postgres 8.3</p>