子查询更新不起作用?

时间:2014-08-20 08:16:41

标签: mysql mysqli phpmyadmin subquery

查询是:

update products set sort_order = (SELECT max(sort_order) from products where branch_id = 1) + 1 where branch_id = 1

sort_order下的所有值当前= 0,我希望它们递增。 显示的错误是:

You can't specify target table 'products' for update in FROM clause

表结构是

products:

product_id (int auto_increment),

product_category_id (int not unique), 

product_name (varchar), 

sort_order (int to specify which will be shown first sort_order ASC),

status (int 1 for active 0 for inactive), 

branch_id (int not unique)

那么子查询应该是什么?

1 个答案:

答案 0 :(得分:0)

<强>更新

啊,现在我得到了你想要的东西。试试这个:

set @row_counter := 0;
update products 
set sort_order = @row_counter := @row_counter + 1
where branch_id = 1
order by whatever_column_determines_the_sort_order;

详细了解用户定义的变量here


原始回答:

操作顺序通常是

  1. FROM clause
  2. WHERE子句
  3. GROUP BY子句
  4. HAVING条款
  5. SELECT条款
  6. ORDER BY子句
  7. 用于select查询。 update也是如此。在update set等于select。这里成功的关键是在from子句中对要更新的表进行(子)查询。

    update products 
    cross join (select max(sort_order) + 1 mso from products where branch_id = 1) sq 
    set sort_order = mso 
    where branch_id = 1;
    

    测试:

    mysql>  create table products(branch_id int, sort_order int);
    Query OK, 0 rows affected (0.03 sec)
    
    mysql> insert into products values (1, 0), (2, 0);
    Query OK, 2 rows affected (0.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> update products cross join (select max(sort_order) + 1 mso from products where branch_id = 1) sq set sort_order = mso where branch_id = 1;
    Query OK, 1 row affected (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
    mysql> select * from products;
    +-----------+------------+
    | branch_id | sort_order |
    +-----------+------------+
    |         1 |          1 |
    |         2 |          0 |
    +-----------+------------+
    2 rows in set (0.00 sec)