在以doc_id为主键的表中工作:

select count(*)+1 from doctor where
exp > (select exp from doctor where doc_id='001');

+------------+
| count(*)+1 |
+------------+
|          2 |
+------------+

但是,当我使用同一个select查询在表中设置字段时,它会报告以下错误:
update doctor set rank=
(  select count(*)+1 from doctor where
   exp > (select exp from doctor where doc_id='001')
) where doc_id='001';

ERROR 1093 (HY000): You can't specify target table 'doctor' for update
in FROM clause

我不明白它指的是哪个目标表引用。有人能解释吗?

最佳答案

此限制记录在MySQL manual中:
当前,无法更新表并从子查询中的同一表中进行选择。
作为解决方法,您可以将子查询包装到另一个子查询中,并避免该错误:

update doctor set rank=
(select rank from (  select count(*)+1 as rank from doctor where
   exp > (select exp from doctor where doc_id='001')
) as sub_query) where doc_id='001';

07-25 22:54
查看更多