如何在一个mySQL查询中更新两个表

时间:2017-03-14 19:06:48

标签: mysql

我在mysql中有以下查询。

UPDATE products A 
JOIN ea_pid B ON A.product_id = B.vpid
JOIN (SELECT product_id, sum(quantity) as quantity2 from ea_products 
GROUP BY product_id) D ON A.product_id = D.product_id
SET A.p_in_stock = (case when B.id = '1' THEN '30' when B.id = '0' THEN D.quantity2 end ) WHERE 1

我想用相同的数字更新第二张表。我尝试按照此解决方案MySQL, update multiple tables with one query但始终收到错误

  

1054 - 未知栏' A.product_id'在' on子句'

这是我到目前为止修改的查询产生了这个错误:

UPDATE products_1 A, products_2 E 
JOIN ea_pid B ON A.product_id = B.vpid
JOIN (SELECT product_id, sum(quantity) as quantity2 from ea_products 
GROUP BY product_id) D ON A.product_id = D.product_id
SET A.p_in_stock = (case when B.id = '1' THEN '30' when B.id = '0' THEN D.quantity2 end ), E.p_in_stock = (case when B.id = '1' THEN '30' when B.id = '0' THEN D.quantity2 end ) WHERE 1

如果我能解决这个问题,我将非常感激。

1 个答案:

答案 0 :(得分:1)

不要将交叉产品与明确的JOIN条款混合使用。我认为由于这个原因,它不会在A子句中识别ON。您还需要products_2的加入条件,否则它将使用相同的值更新所有行。

UPDATE products_1 AS a
JOIN products_2 AS e ON a.product_id = e.product_id
JOIN ea_pid AS b ON a.product_id = b.vpid
JOIN (SELECT product_id, SUM(quantity) AS quantity2
      FROM ea_products
      GROUP BY product_id) AS d
    ON a.product_id = d.product_id
SET a.p_in_stock = (CASE b.id
                    WHEN '1' THEN '30'
                    WHEN '0' THEN d.quantity2
                    END),
    e.p_in_stock = (CASE b.id
                    WHEN '1' THEN '30'
                    WHEN '0' THEN d.quantity2
                    END)