[英]Sort Order SQL Table
我有包含以下信息的 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
您可以在update
使用order by
:
set @rn := 0
update cities
set sort_order = (@rn := @rn + 1)
order by state_id, city;
假设 MySQL 8.0,您可以使用row_number()
。
我实际上不会将这些派生信息存储在表本身中; 当数据更改时,您可能需要对多行重新编号。
相反,您可以在需要时即时计算此信息,或使用视图:
select c.*, row_number() over(order by state_id, city) sort_order
from cities c
在早期版本中,您可以使用变量实现相同的结果:
select c.*, (@rn := @rn + 1) sort_order
from cities c
cross join (select @rn := 1 rn) r
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.