Mysql,按日期顺序更新

时间:2016-02-17 05:35:09

标签: mysql sql-update sql-order-by

我创建了一个包含此查询的表:

CREATE TABLE `m_stock_onhand` (
  `m_stock_onhand_id` int(11) NOT NULL AUTO_INCREMENT,
  `app_org_id` int(11) DEFAULT NULL,
  `m_product_id` int(11) NOT NULL,
  `m_inout_date` date NOT NULL,
  `prev_quantity` int(11) NOT NULL,
  `in_quantity` int(11) NOT NULL,
  `out_quantity` int(11) NOT NULL,
  `balance_quantity` int(11) NOT NULL,
  `latest` char(1) NOT NULL,
  `update_user` int(11) DEFAULT NULL,
  `update_date` datetime DEFAULT NULL,
  PRIMARY KEY (`m_stock_onhand_id`),
  UNIQUE KEY `m_product_id` (`m_product_id`,`m_inout_date`,`app_org_id`)
) ENGINE=InnoDB AUTO_INCREMENT=93167 DEFAULT CHARSET=utf8;

我想更新2字段prev_quantity和balance_quantity,但不是有效的statemant。

UPDATE m_stock_onhand e,
       (SELECT @n := 0) m
    SET e.prev_quantity = @n,
    e.balance_quantity = (@n := @n + e.in_quantity - e.out_quantity)
    WHERE e.m_product_id = '3967' 
order by e.m_inout_date;

此查询在没有“order by”语句的情况下工作,但是,它的计算无效,导致计算必须对datetime有效。

1 个答案:

答案 0 :(得分:0)

我认为你不能这样做(但我可能会弄错!)。

相反,您可以将SELECT加入UPDATE,就像这样......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,total INT NOT NULL,running_total INT NULL);

INSERT INTO my_table (total) VALUES (1),(3),(1),(1),(4),(3),(1),(2),(5);

SELECT * FROM my_table x ORDER BY id;
+----+-------+---------------+
| id | total | running_total |
+----+-------+---------------+
|  1 |     1 |          NULL |
|  2 |     3 |          NULL |
|  3 |     1 |          NULL |
|  4 |     1 |          NULL |
|  5 |     4 |          NULL |
|  6 |     3 |          NULL |
|  7 |     1 |          NULL |
|  8 |     2 |          NULL |
|  9 |     5 |          NULL |
+----+-------+---------------+

UPDATE my_table x 
  JOIN 
     ( SELECT x.*, @i:=@i+total i FROM my_table x,(SELECT @i:=0) vars ORDER BY id) y 
    ON y.id = x.id 
   SET x.running_total = i;
Query OK, 9 rows affected (0.00 sec)
Rows matched: 9  Changed: 9  Warnings: 0

SELECT * FROM my_table ORDER BY id;
+----+-------+---------------+
| id | total | running_total |
+----+-------+---------------+
|  1 |     1 |             1 |
|  2 |     3 |             4 |
|  3 |     1 |             5 |
|  4 |     1 |             6 |
|  5 |     4 |            10 |
|  6 |     3 |            13 |
|  7 |     1 |            14 |
|  8 |     2 |            16 |
|  9 |     5 |            21 |
+----+-------+---------------+