如何在多个条件 mysql 下将列位置更新为 table

how do i update column position into table with several conditions mysql

我有一个 table 这样的:

+----+------------+-------------+----------+------------+-----------+
| id | product_id | category_id | position | createdAt  | status_id |
+----+------------+-------------+----------+------------+-----------+
|  1 |        246 |           1 |        1 | 2020-01-01 |         1 |
|  2 |        247 |           1 |        2 | 2020-01-02 |         0 |
|  3 |        248 |           8 |        3 | 2020-01-03 |         1 |
|  4 |        249 |           8 |        4 | 2020-01-04 |         0 |
|  5 |        250 |           1 |        5 | 2020-01-04 |         1 |
|  6 |        251 |           8 |        6 | 2020-01-05 |         1 |
+----+------------+-------------+----------+------------+-----------+

如何使用 category_id = 8 和 status_id = 1 下订单并更新 product_id 的列位置,但是如果 status_id 从 1 更新为 0,然后根据 table 删除 product_id 上的订单,我的预期结果应该是这样的:

+----+------------+-------------+----------+------------+-----------+
| id | product_id | category_id | position | createdAt  | status_id |
+----+------------+-------------+----------+------------+-----------+
|  1 |        246 |           1 |        1 | 2020-01-01 |         1 |
|  2 |        247 |           1 |        2 | 2020-01-02 |         0 |
|  3 |        248 |           8 |        1 | 2020-01-03 |         1 |
|  4 |        249 |           8 |        4 | 2020-01-04 |         0 |
|  5 |        250 |           1 |        5 | 2020-01-04 |         1 |
|  6 |        251 |           8 |        2 | 2020-01-05 |         1 |
+----+------------+-------------+----------+------------+-----------+

我试过

    UPDATE position SET position = (how to order it) 
    WHERE category_id = 8 and status_id = 1
    

更新: 我试过这个:

UPDATE product_categories pc1 SET pc1.position = 
(SELECT  (@row:=@row+1) FROM product_categories pc2 WHERE
pc2.status = 1 AND pc2.category_id = 8 ORDER BY pc2.createdAt);

但它会产生这样的错误Error Code: 1093. You can't specify target table 'pc1' for update in FROM clause

更新:我试过这个

SET @row := 0;
SET SQL_SAFE_UPDATES = 0;
UPDATE product_categories pc1 SET pc1.position = 
(SELECT  (@row:=@row+1) FROM (SELECT pc2.product_id FROM product_categories pc2 WHERE
pc2.status = 1 AND pc2.category_id = 8 ORDER BY pc2.createdAt) AS a);
SET SQL_SAFE_UPDATES = 1;

出现这样的错误:Error Code: 1242. Subquery returns more than 1 row

您或许可以使用此更新:

UPDATE product_categories a 
  JOIN
     (SELECT @row:=@row+1 pos, b.* 
      FROM product_categories b 
      WHERE category_id=8 AND status_id=1) b
   ON a.id=b.id 
   AND a.product_id=b.product_id 
   AND a.category_id=b.category_id
   AND a.status_id=b.status_id
SET a.position=b.pos;

这是一个演示 fiddle: https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=8bc4d1844aff2fbfa0210c4c760cd07a