如何根据MySQL表中的时间戳重置主键?

时间:2012-07-24 22:55:47

标签: mysql sorting primary-key

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

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;

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

显示创建表的输出

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我知道你已经接受了答案,但为了后代,我想用一个更简单的解决方案。 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;