Reordering of column data in mysql

后端 未结 4 1434
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 11:47

I have a table like so:

categoryID      categoryName
----------------------------
     1            A
     2            B
     3            C
4条回答
  •  借酒劲吻你
    2021-01-07 12:39

    If the number of changes is rather small you can generate a clumsy but rather efficient UPDATE statement if the you know the ids of the involved items:

    UPDATE categories
    JOIN (
        SELECT 2 as categoryID, 3 as new_order
        UNION ALL
        SELECT 3 as categoryID, 4 as new_order
        UNION ALL
        SELECT 4 as categoryID, 2 as new_order) orders
    USING (categoryId)
    SET `order` = new_order;
    

    or (which I like less):

    UPDATE categories
    SET `order` = ELT (FIND_IN_SET (categoryID, '2,3,4'),
                       3, 4, 2)
    WHERE categoryID in (2,3,4);
    

    UPD:

    Assuming that you know the current id of the category (or its name), its old position, and its new position you can use the following query for moving a category down the list (for moving up you will have to change the between condition and new_rank computation to rank+1):

    SET @id:=2, @cur_rank:=2, @new_rank:=4;
    
    UPDATE t1
    JOIN (
      SELECT categoryID, (rank - 1) as new_rank
      FROM t1
      WHERE rank between @cur_rank + 1 AND @new_rank
      UNION ALL
      SELECT @id as categoryID, @new_rank as new_rank
    ) as r
    USING (categoryID)
    SET rank = new_rank;
    

提交回复
热议问题