我有一个包含2列别名(全部为小写)和排序
的表格如何根据字母别名按字母顺序将数字0设置为x?
根据另一个查询的排序顺序更新列(按别名选择mytable顺序)?
to get
alias | ordering
abf-ergterw | 0
crdsv-dfgdfg | 2
bggg-rgewrdg | 1
dxgg-rgewrdg | 3
类似
SET @count = 0;
UPDATE mytable SET ordering = @count:= @count + 1;
但基于列别名 a = 1,b = 2,c = 3,....
谢谢
答案 0 :(得分:0)
您可以使用ROW_NUMBER
:
SELECT *, ROW_NUMBER() OVER(ORDER BY alias ASC) - 1 AS ordering
FROM tab
ORDER BY ordering;
UPDATE
:
UPDATE tab a
JOIN (
SELECT *, ROW_NUMBER() OVER(ORDER BY alias ASC) - 1 AS ord
FROM tab
) b ON a.alias = b.alias
SET a.ordering = b.ord
;
<强> MySQL 8.0+ Demo 强>
答案 1 :(得分:0)
您可以在UPDATE语句中使用ORDER BY子句:
SET @count = -1;
UPDATE mytable
SET ordering = @count:= @count + 1
ORDER BY alias ASC;