如何更新非空列值以自动增加列值(mysql)?

How to update not-null column value to auto-increment column value (mysql)?

我有一个 table 订单有两列:

  1. id(auto_increment 关键字段)
  2. order_id(非空字段)。

我想用 id 字段的值更新 order_id 意味着如果 id = 1 那么 order_id = 1,如果 id = 2 那么 order_id = 2 等等。 ...

如何使用 MySQL 存储过程来做到这一点?

感谢您的帮助。

一个选项是:

mysql> DROP TABLE IF EXISTS `orders`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `orders` (
    ->   `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    ->   `order_id` INT UNSIGNED NOT NULL
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> DELIMITER //

mysql> DROP PROCEDURE IF EXISTS `new_procedure`//
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE PROCEDURE `new_procedure`()
    -> BEGIN
    ->   DECLARE `last_insert_id` INT UNSIGNED;
    ->   INSERT INTO `orders` (`id`, `order_id`)
    ->   VALUES (NULL, 0);
    ->   SET `last_insert_id` := LAST_INSERT_ID();
    ->   UPDATE `orders`
    ->   SET `order_id` = `last_insert_id`
    ->   WHERE `id` = `last_insert_id`;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> CALL `new_procedure`();
Query OK, 1 row affected (0.00 sec)

mysql> CALL `new_procedure`();
Query OK, 1 row affected (0.00 sec)

mysql> CALL `new_procedure`();
Query OK, 1 row affected (0.00 sec)

mysql> SELECT
    ->   `id`,
    ->   `order_id`
    -> FROM
    ->   `orders`;
+----+----------+
| id | order_id |
+----+----------+
|  1 |        1 |
|  2 |        2 |
|  3 |        3 |
+----+----------+
3 rows in set (0.00 sec)