MySQL:如何订购和设置ID?

时间:2018-09-02 11:17:21

标签: mysql sql id

我已经用谷歌搜索,但是找不到解决方案。

我有两列,分别为order_idname。我要先ORDER BY name,然后SET升序order_id

赞:

order_id   name
1          Arya
2          Herbert
3          Paul
4          Peter
5          Tiffany

我的id列为int(4),默认值为0。不是PRIMARYUNIQUE。 (它也不是主要ID。主要ID当然是PRIMARY

我该如何使用SQL?

3 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER(MySQL 8.0 +):

SELECT name, ROW_NUMBER() OVER(ORDER BY name) AS rn
FROM tab
ORDER BY rn;

更新:

UPDATE tab
SET order_id = (SELECT rn FROM (SELECT name,ROW_NUMBER() OVER(ORDER BY name) AS rn
                                FROM tab)s
                WHERE s.name = tab.name); -- assuming that name is UNIQUE

DBFidde Demo

答案 1 :(得分:2)

对于<8.0版,您可以使用以下版本:

select @rn := 0;

UPDATE tbl T1
JOIN (select @rn := @rn + 1 rn, `name` from tbl order by `name`) T2
  ON T1.`name` = T2.`name`
SET T1.order_id = T2.rn

Demo

与您的问题有关的有用文章:MySQL UPDATE JOIN

答案 2 :(得分:0)

由于您的mysql版本低于8.0,因此您必须手动生成orderid 下面可以帮助您

select  t.*, 
                   @rownum := @rownum + 1 AS order_id from 
            (
            select * from
             tab o order by name asc
            )  as t , (SELECT @rownum := 0) r

http://www.sqlfiddle.com/#!9/ae3fda/3