我正在尝试使用子查询创建的另一张表中的数据来更新一张表中的两个属性/列。这是我的代码。
CREATE TABLE tmpempcnt (SELECT projno, count(*) as ct FROM Pworks group by projno);
UPDATE Proj
INNER JOIN tmpempcnt ON Proj.projno = tmpempcnt.projno
SET Proj.empcnt = tmpempcnt.ct;
CREATE TABLE (SELECT projno as p, SUM(hours) as h FROM Pworks GROUP BY projno);
UPDATE Proj
INNER JOIN tmphrstotal ON Proj.projno = tmphrstotal.p
SET Proj.hrstotal = tmphrstotal.h;
有没有一种方法无需事先创建表? 谢谢
答案 0 :(得分:1)
mysql允许多表更新https://dev.mysql.com/doc/refman/8.0/en/update.html。就您而言
drop table if exists pworks,proj;
create table proj(projno int,empcnt int, hrstotal int);
create table pworks(projno int,hours int);
insert into proj values(1,null,null);
insert into pworks values
(1,10),(1,10);
update proj
join (select projno,count(*) cnt,sum(hours) hrs from pworks group by projno) s on s.projno = proj.projno
set empcnt = cnt,hrstotal = hrs;
可能会