首页 > 解决方案 > 排序顺序 SQL 表

问题描述

我有带有以下信息的 SQL 表:

    CREATE TABLE `cities` (
  `city_id` int(11) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state_id` int(11) NOT NULL,
  `is_default` int(1) DEFAULT '1',
  `is_active` int(1) NOT NULL DEFAULT '1',
  `sort_order` int(11) NOT NULL DEFAULT '9999',
  `lang` varchar(10) NOT NULL DEFAULT 'en',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

问题是 sort_order 是空的...

我如何首先将表格排序为 state_id -> 然后将城市排序为字母并从 1 - * 填充 sort_order

标签: mysqlsql

解决方案


您可以order byupdate

set @rn := 0

update cities
    set sort_order = (@rn := @rn + 1)
    order by state_id, city;

推荐阅读