根据日期时间列重置auto_increment

时间:2015-10-24 18:47:33

标签: mysql datetime auto-increment reset

我正在通过phpMyAdmin使用MySQL。我需要重置我的数据库中的一个表中的ID字段,但我需要根据每行的发布日期来完成。我一直在寻找各处,我似乎无法找到解决方案:(

以下代码行工作正常,但根据datetime列不能完全满足我的要求:

SET @count = 0;
UPDATE `table_name` SET `table_name`.`ID` = @count:= @count + 1;

所以这就是我所拥有的:

+----+---------------------+
| ID | post_date           |
+----+---------------------+
| 1  | 2013-11-04 20:06:28 |
| 2  | 2012-03-30 11:20:22 |
| 3  | 2014-06-26 22:59:51 |
+----+---------------------+

这就是我需要的:

+----+---------------------+
| ID | post_date           |
+----+---------------------+
| 1  | 2005-08-02 16:51:48 |
| 2  | 2005-08-02 16:59:36 |
| 3  | 2005-08-02 17:01:54 |
+----+---------------------+

先谢谢你,伙计们:)

2 个答案:

答案 0 :(得分:1)

尝试这个,虽然是一个简单的方法。

  

但是你会失去与其他桌子的所有关系   重置PRIMARY ID密钥。

# Copy entire table to a temporary one based on the publication date
CREATE TEMPORARY TABLE IF NOT EXISTS `#temp_table` AS SELECT * FROM `wp_posts` ORDER BY `post_date`;

# Drop `ID` column from the temporary table
ALTER TABLE `#temp_table` DROP COLUMN `ID`;

# Reset the table `wp_posts` as well as its `ID`
TRUNCATE TABLE `wp_posts`;

# Exclude `ID` column in the INSERT statement below
INSERT INTO  `wp_posts`(`post_author`, `post_date`, ..., `comment_count`) SELECT * FROM `#temp_table`;

# Remove the temporary table
DROP TABLE `#temp_table`;

另见下面的WP3.0的ERD, enter image description here

参考:https://codex.wordpress.org/Database_Description/3.3

答案 1 :(得分:0)

尝试使用以下脚本执行此操作。它选择表格的每一行,并按行日期升序对行进行排序。然后你的Update-Command将在循环中执行。

将表的ID类型添加到DECLARE-Statement并更改 UPDATE-Statement中的字段名称为您的ID列名称。

 BEGIN
        DECLARE col_id BIGINT;
        DECLARE stepLoopDone BOOLEAN DEFAULT FALSE;
        DECLARE counter INT DEFAULT 1;

        DECLARE ORDER_CURSOR CURSOR FOR

            SELECT id
            FROM wp_posts
            ORDER BY post_date ASC;

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET stepLoopDone = TRUE;
        OPEN ORDER_CURSOR;

        myLoop: LOOP
            FETCH ORDER_CURSOR INTO col_id;

            IF stepLoopDone THEN
                LEAVE myLoop;
            END IF;

            /*YOUR UPDATE COMMAND*/
            UPDATE wp_posts
            SET id = counter
            WHERE id = col_id;
            /*YOUR UPDATE COMMAND*/

            SET counter = counter + 1;

        END LOOP;

        CLOSE ORDER_CURSOR;
END