我有一个包含两列的表订单:
我想用id字段的值更新order_id意味着如果id = 1则order_id = 1,如果id = 2则则order_id = 2等等......
如何使用MySQL存储过程执行此操作?
感谢您的帮助。
答案 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)