mysql update 1记录基于多个其他记录的值

时间:2014-05-19 20:42:35

标签: mysql stored-procedures

SQL FIDDLE http://sqlfiddle.com/#!2/cbebfb/1

我在ProductTemp中使用SKU" Fruits&amp ;;坚果礼品篮"其中ProductID = 1。

ProductId 1" Fruits& Nuts Gift Basket"由14个包含ProductNo&#s;(525,535,523,502,506,526,524,515,520,514,532,527,497,526)的儿童产品组成。

如果任何儿童产品(水果或坚果)数量低于规定的阈值(例如小于3),请设置"水果和水果。 Nuts Gift Basket",ProductID 1活动状态TO" 0"。

期望的结果:我想禁用" Fruits&坚果礼品篮"如果任何儿童产品低于阈值。

UPDATE ProductTemp
     SET Active = CASE
        WHEN (ProductNo) = (535) AND (Quantity < 3) THEN 0
        WHEN (ProductNo) = (525) AND (Quantity < 3) THEN 0
        WHEN (ProductNo) = (523) AND (Quantity < 2) THEN 0
        WHEN (ProductNo) = (526) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (524) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (502) AND (Quantity < 2) THEN 0
        WHEN (ProductNo) = (515) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (506) AND (Quantity < 2) THEN 0
        WHEN (ProductNo) = (520) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (514) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (532) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (527) AND (Quantity < 1) THEN 0
        WHEN (ProductNo) = (497) AND (Quantity < 1) THEN 0
        ELSE Active
      END
    WHERE ProductID = 1

我还修改了@strawberry提供的重构查询

UPDATE ProductTemp SET Active = CASE WHEN (ProductNo IN(535,525) AND Quantity < 3) OR (ProductNo IN(523,502,506) AND Quantity < 2) OR (ProductNo IN(526,524,515,520,514,532,527,497) AND Quantity < 1) THEN 0 ELSE Active END WHERE ProductID = 1; 运行上面的查询---&#34; 0行受影响的行匹配:1更改:0警告:0&#34;

1 个答案:

答案 0 :(得分:0)

顺便说一句,我认为你的查询可以改写如下......

UPDATE my_table 
   SET active = CASE WHEN (ProductNo IN(535,525) AND Quantity < 3) 
                       OR (ProductNo IN(523,502,506) AND Quantity < 2) 
                       OR (ProductNo IN(526,524,515,520,514,532,527,497) AND Quantity < 1) 
                     THEN 0 ELSE active
                 END;

参考下面的评论,并举例说明,请考虑以下内容......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(product_no INT NOT NULL PRIMARY KEY,quantity INT NOT NULL);

INSERT INTO my_table VALUES (35,4),(525,2);

SELECT * FROM my_table;
+------------+----------+
| product_no | quantity |
+------------+----------+
|         35 |        4 |
|        525 |        2 |
+------------+----------+

SELECT *,(product_no IN(35,525) AND quantity < 3) x FROM my_table;
+------------+----------+---+
| product_no | quantity | x |
+------------+----------+---+
|         35 |        4 | 0 |
|        525 |        2 | 1 |
+------------+----------+---+