[英]Sort Order SQL Table
i have SQL Table with following Infos :我有包含以下信息的 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;
The Problem is sort_order is empty ...问题是 sort_order 为空...
How can i sortorder the Table first to state_id -> then order the city to Alphabetic and fill the sort_order from 1 - *我如何将表先排序到 state_id -> 然后将城市排序为字母并从 1 - * 填充 sort_order
You can use order by
in an update
:您可以在
update
使用order by
:
set @rn := 0
update cities
set sort_order = (@rn := @rn + 1)
order by state_id, city;
Assuming MySQL 8.0, you can use row_number()
.假设 MySQL 8.0,您可以使用
row_number()
。
I would not actually storing this derived information in the table itself;我实际上不会将这些派生信息存储在表本身中; when data changes, you might need to renumber many rows.
当数据更改时,您可能需要对多行重新编号。
Instead, you can compute this information on the fly when needed, or use a view:相反,您可以在需要时即时计算此信息,或使用视图:
select c.*, row_number() over(order by state_id, city) sort_order
from cities c
In earlier versions, you can achieve the same results with variables:在早期版本中,您可以使用变量实现相同的结果:
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.