1

我知道我可以通过这种方式重置主键:

ALTER TABLE `users` DROP `id`;
ALTER TABLE `users` AUTO_INCREMENT = 1;
ALTER TABLE `users` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

但我想知道如何调整它以根据我的时间戳列中的时间戳应用主键,即具有最旧时间戳的行获得值 1,下一个最旧的值 2,等等。

SHOW CREATE TABLE 的输出

CREATE TABLE `tracks` (
 `id` int(10) unsigned NOT NULL auto_increment,
 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
 `from_user` varchar(50) NOT NULL,
 `source_filename` varchar(80) NOT NULL,
 `uploaded_page` varchar(50) NOT NULL,
 `operating_system` varchar(50) NOT NULL,
 `browser` varchar(50) NOT NULL,
 `os_browser_version` varchar(200) NOT NULL,
 `title` varchar(100) NOT NULL,
 `artist` varchar(60) NOT NULL,
 `album` varchar(120) NOT NULL,
 `genre` varchar(120) NOT NULL,
 `format` varchar(10) NOT NULL,
 `bitrate` mediumint(9) NOT NULL,
 `conversion_needed` tinyint(1) NOT NULL COMMENT 'if not mp3, or higher than 192kbps',
 `conversion_successful` tinyint(1) NOT NULL,
 `art_extracted` tinyint(1) NOT NULL,
 `art_location` varchar(200) NOT NULL,
 `file_location` varchar(200) NOT NULL,
 `status` varchar(500) NOT NULL,
 PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=96 DEFAULT CHARSET=utf8
4

2 回答 2

3

创建一个名为的新表users2,其结构与以下内容相同users

CREATE TABLE users2 LIKE users;

然后运行这个语句:

INSERT INTO users2
(col1, col2, ... coln)
SELECT col1, col2, ... coln
FROM users
ORDER BY your_timestamp

对于您的特定表:

INSERT INTO tracks2
(`timestamp`,`from_user`,`source_filename`,`uploaded_page`,`operating_system`,`browser`,`os_browser_version`,`title`,`artist`,`album`,`genre`,`format`,`bitrate`,`conversion_needed`,`conversion_successful`,`art_extracted`,`art_location`,`file_location`,`status`)
SELECT `timestamp`,`from_user`,`source_filename`,`uploaded_page`,`operating_system`,`browser`,`os_browser_version`,`title`,`artist`,`album`,`genre`,`format`,`bitrate`,`conversion_needed`,`conversion_successful`,`art_extracted`,`art_location`,`file_location`,`status`
FROM tracks
ORDER BY timestamp
于 2012-07-24T23:04:34.507 回答
2

我知道您已经接受了答案,但是为了后代,我想提出一个更简单的解决方案。MySQL 允许您使用 重新排序表的行,因此您可以通过在原始示例中再ALTER TABLE...ORDER BY...添加一条语句轻松地做到这一点:ALTER TABLE

ALTER TABLE `users` DROP COLUMN `id`;
ALTER TABLE `users` ORDER BY `timestamp`;
ALTER TABLE `users` AUTO_INCREMENT = 1;
ALTER TABLE `users` ADD COLUMN `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
于 2012-07-24T23:48:55.070 回答