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

时间:2016-12-06 17:12:18

标签: mysql database stored-procedures auto-increment

我有一个包含两列的表订单:

  1. id(auto_increment key field)
  2. order_id(非空字段)。
  3. 我想用id字段的值更新order_id意味着如果id = 1则order_id = 1,如果id = 2则则order_id = 2等等......

    如何使用MySQL存储过程执行此操作?

    感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

一个选项是:

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)