如何在SQL中使用join而不是子查询?

时间:2015-06-02 07:11:34

标签: sql sql-server join

我有3张桌子:

  • Department(Deptid主键),Deptname)

  • Employee(Empid(主键),Depid(外键引用Deptid),Empname)

  • Salary(月,Eid(外键指Empid),slry)

我有一个子查询:

select Eid, sum(slry) as salarysum 
from Salary 
where Eid in (select Empid from Employee where Depid = 1) 
group by Eid

我需要使用join而不是此子查询,但我不知道如何在此上下文中使用?

请帮我解决这个问题!

3 个答案:

答案 0 :(得分:1)

由于EmpidEmployee表的主键,因此您可以将Salary加入Employee表,而无需担心重复Salary行。

您可以使用像这样的查询

SELECT Eid,sum(slry) as salarysum
FROM Salary S
inner join Employee E on E.Empid = S.Eid 
WHERE Depid=1
group by Eid

答案 1 :(得分:0)

检查以下查询是否有帮助:

SELECT 
    Eid,sum(slry)as salarysum 
FROM Salary 
INNER JOIN Employee ON Empid = Eid and Depid=1
GROUP BY Eid

答案 2 :(得分:0)

尝试这样的事情。制作JOIN on e.Empid = s.Eid

select s.Eid, sum(slry) as salarysum
from Salary s
inner join Employee e on e.Empid = s.Eid
where Depid = 1
group by s.Eid