mysql - 排序顺序 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
解决方案
您可以order by
在update
:
set @rn := 0
update cities
set sort_order = (@rn := @rn + 1)
order by state_id, city;
推荐阅读
- javafx - TreeTableView 将嵌套值添加到 TreeItemPropertyValueFactory
- android - 带有圆形按钮的Android底部导航
- javascript - Typescript(Javascript)中奇怪的类属性分配:'?='
- php - 完全隐藏wordpress页面
- image - 无法在颤振应用程序中以圆形渲染图像
- reactjs - 带有 API 调用的函数
- vue.js - 在服务器上部署本地 Vueapp
- html - 如何使颜色占宽度的 100%
- android - Firebase A/B 测试版本定位
- css - 为什么我的 AG Grid 不能正确渲染行样式?