我正在尝试针对下表编写查询
Table A
========
ID
A1
Table B
=========
ID
B1
查询 1:
update A
set A.A1 =(
select count (distinct b1)
from B
join A on A.ID = B.ID
Group by B1
给我一个错误-
MySQL Error Code: 1093. you can't specify target table for update in FROM clause
因此我尝试了以下查询:
查询 2:
update A
set A1 = (
select count from (
select count( distinct B1) as count
from B
join A on A.ID = B.ID
group by ID
) s
);
上面的查询给我错误
Error Code: 1242. Subquery returns more than 1 row
我试过如下创建暂存表并且它有效。
查询 3:
insert into stg
(
par1,
par2
)
select ID, count( distinct B1) from B group by ID;
update A
set A1 = ( select par2 from stg where A.pm = stg.par1 );
有没有更好的方法来做同样的事情?
谢谢
最佳答案
如果您只是计数而没有引用计数,则跳过 GROUP BY
改变。
update A
JOIN (select count( distinct B1) as count FROM B JOIN A on A.ID = B.ID) B
set A.A1=B.count;
关于MySQL 错误代码 : 1093. 您无法在 FROM 子句中指定要更新的目标表 'xyz',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050998/