in reply to Calculating previous/next from database

If you have the id as a separate column as opposed to embedded in the name, you can easily do this with:
SELECT * FROM images WHERE id > ? LIMIT 1
That would be for the ++ scenario.

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re^2: Calculating previous/next from database
by ikegami (Patriarch) on May 31, 2008 at 04:05 UTC
    Not quite. What you have won't return all the records in the table when called repeatedly. For that you need
    SELECT * FROM images WHERE id > ? ORDER BY id LIMIT 1
Re^2: Calculating previous/next from database
by Anonymous Monk on May 31, 2008 at 05:21 UTC
    A problem I see with this approach would be sending three queries to the database each time it loads. One for ++, one for --, and the one the OP is using for the real query.
      Meh. If your requirement is a single query, then you need to implement a linked list in the database. This isn't that hard, but it requires that all inserts and deletes update 3 rows vs. just selects doing three queries. This probably is ok.
      CREATE TABLE images ( id INT ,prev_id INT ,next_id INT ,other_columns_here );
      Then, to get everything in a single query, you do:
      SELECT * FROM images WHERE ( (id=?) OR (next_id=?) OR (prev_id=?) );
      Not that hard. :-)

      My criteria for good software:
      1. Does it work?
      2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

      Only if this could work ...

      -- changed "union" to "union all" select id from table where id > ? order by id asc limit 1 UNION ALL select id from table where id < ? order by id desc limit 1

      ... does not work in Sybase for (a) "order by" clause does not go with "union all" or in derived table creation; (b) there is no "limit" clause, just "rowcount" option per SQL session/transaction.

        You can do it in a little more convoluted way not using UNION at all:

        SELECT * FROM table WHERE id=(SELECT id FROM table WHERE id>? ORDER BY id ASC LIMIT 1) OR id=(SELECT id FROM table WHERE id<? ORDER BY id DESC LIMIT 1)

        Careful with that hash Eugene.