Вопрос

I have an application where I cannot change the way the app sorts the output. It wants to use a "sortorder" column no matter what.

I also have a large table where the sortorders are all currently zero. I want to populate those fields automatically, based on the alphabetical order of the "itemname" column.

The table is like this:

id     itemname     sortorder
1       A item         0
2       Big item       0
3       Cool item      0
4       Bad item       0

I want to run a query to make it be like this:

id     itemname     sortorder
1       A item         10
2       Big item       30
3       Cool item      40
4       Bad item       20

What's the best approach to do this?

Это было полезно?

Решение

UPDATE TableName a
       INNER JOIN
      (
        SELECT  A.id, 
                A.itemName,
                @sort := @sort + 10 so
        FROM    TableName a,
                (SELECT @sort:=0) b
        ORDER   BY itemName, id
        ) b ON a.id = b.ID
SET a.sortorder = b.so
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top