我正在尝试用我的SQL代码做两件事。我希望它从另一个列(小时)复制数据,这些数据位于另一个表(工作表)中,并将其放入另一个表(Employee-表)中的新列(numHours)中。但是,我希望它使用每个员工ID(eid)工作小时数的总和,然后将该总和放入新列中。
这是我写的,但有两件事是错的。当我执行select语句时,每个员工ID都具有相同的工作小时数。当我运行整个语句时,我收到此错误
子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。 声明已经终止。
UPDATE Employee
SET numHours= (SELECT sum(w.hours) AS totalHours From works w, Employee e WHERE
numHours IS NULL AND e.eid = w.eid Group by w.eid);
这些是我的表
CREATE TABLE Employee(
eid INT,
ename VARCHAR(30),
age INT,
salary INT,
CONSTRAINT Pk_key_eid PRIMARY KEY (eid)
);
CREATE TABLE Department(
did INT,
dname VARCHAR(30),
budget int,
managerid INT,
CONSTRAINT Validate_managerid CHECK(managerid < 1000),
CONSTRAINT Pk_key_did PRIMARY KEY (did)
);
CREATE TABLE Works(
eid INT,
did INT,
hours INT,
CONSTRAINT fk_key_eid FOREIGN KEY (eid) REFERENCES Employee (eid) ON DELETE CASCADE,
CONSTRAINT fk_key_Did FOREIGN KEY (did) REFERENCES Department (did) ON DELETE CASCADE
);
我如何正确编码?
答案 0 :(得分:1)
我相信你想要这个:
UPDATE Employee
SET numHours= (SELECT sum(w.hours) From works w WHERE employee.eid = w.eid)
WHERE numHours IS NULL;
注意:
numHours
上的条件属于UPDATE
,而不属于子查询。FROM
子句中使用逗号!)。GROUP BY
。答案 1 :(得分:1)
使用JOIN和UPDATE:
UPDATE E
SET E.numHours=H.totalHours
FROM Employee E JOIN
(Select sum(hours) AS totalHours,eid
From works
Group by eid)H on H.eid=E.eid
WHERE E.numHours IS NULL
<强>解释强>
内部查询将选择每位员工的总小时数。然后用它来更新Employee
表。