How can I reorder rows in sql database

后端 未结 14 1826
忘了有多久
忘了有多久 2020-11-28 03:24

Is it possible to reorder rows in SQL database? For example; how can I swap the order of 2nd row and 3rd row\'s values?

The order of the row is important to me since

相关标签:
14条回答
  • 2020-11-28 03:51

    As others have mentioned, it's not a good idea to depend on the physical order of the database table. Relational tables are conceptually more like unordered sets than ordered lists. Assuming a certain physical order may lead to unpredictable results.

    Sounds like what you need is a separate column that stores the user's preferred sort order. But you'll still need to do something in your query to display the results in that order.

    It is possible to specify the physical order of records in a database by creating a clustered index, but that is not something you'd want to do on an arbitrary user-specified basis. And it may still lead to unexpected results.

    0 讨论(0)
  • 2020-11-28 03:55

    Here is a stored procedure script to increment or decrement (one at a time) in MySQL.

    Note, MySQL doesn't allow you to select in the same query you're updating so the above answers don't work.

    I have also set it to return an error if there is no item above / below if you're incrementing / decrementing, respectively.

    DELIMITER $$
    CREATE PROCEDURE `spReorderSequenceItems` (
      IN _SequenceItemId INT,
      IN _SequenceId INT,
      IN IncrementUp TINYINT,
      OUT Error VARCHAR(255)
    )
    
    BEGIN
      DECLARE CurrentPosition INT;
    
      SELECT Position INTO CurrentPosition
      FROM tblSequenceItems
      WHERE SequenceItemId = _SequenceItemId;
    
      IF IncrementUp = 1 THEN
        IF (
          SELECT Position
          FROM tblSequenceItems 
          WHERE Position = CurrentPosition + 1 AND SequenceId = _SequenceId
        ) THEN
          UPDATE tblSequenceItems
            SET Position = Position - 1
            WHERE Position = CurrentPosition + 1 AND SequenceId = _SequenceId;
          UPDATE tblSequenceItems
            SET Position = Position + 1
            WHERE SequenceItemId = _SequenceItemId;
        ELSE 
          SELECT 'No Item Above' AS _Error INTO Error;
        END IF;
      ELSE
        IF (
          SELECT Position
          FROM tblSequenceItems 
          WHERE Position = CurrentPosition - 1 AND SequenceId = _SequenceId
        ) THEN
          UPDATE tblSequenceItems
            SET Position = Position + 1
            WHERE Position = CurrentPosition - 1 AND SequenceId = _SequenceId;
          UPDATE tblSequenceItems
            SET Position = Position - 1
            WHERE SequenceItemId = _SequenceItemId;
        ELSE
          SELECT 'No Item Below' AS _Error INTO Error;
        END IF;
      END IF;
    END
    $$
    DELIMITER ;
    

    Call it with

    CALL spReorderSequenceItems(1, 1, 1, @Error);
    SELECT @Error;
    
    0 讨论(0)
提交回复
热议问题