5

这适用于doc_id主键为表的表:

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

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

但是当我使用相同的选择查询在表中设置字段时,它会报告以下错误:

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

我不明白它在说哪个目标表引用。有人可以解释吗?

4

3 回答 3

10

此限制记录在MySQL 手册中:

目前,您无法在子查询中更新表并从同一个表中进行选择。

作为一种解决方法,您可以将子查询包装在另一个子查询中并避免该错误:

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';
于 2011-03-15T19:46:01.140 回答
1

您不能在 from 子句的子查询中使用正在更新的表。尝试连接或双子查询:)

于 2011-03-15T19:00:35.503 回答
1

我认为这可能是因为您正在同一张桌子上阅读和写作。这可能是一种阻止写入的预防方法,因为您的更新可能会影响正在读取的数据。

您可能需要将子查询分离为使用中间虚拟表。

于 2011-03-15T19:03:15.010 回答