2

我有 2 个表员工和薪水员工 => ID,姓名字段

Salary => Sid, EId(Foriegn key) , Month, Salary

Employee 
ID  Name
1   a
2   b
3   c

Salary 
Sid Eid Month Salary
1    1   Jan   10
2    2   Jan   10
3    3   Jan   10 
4    1   Feb   10
5    3   Feb   10
6    1   Mar   10
7    2   Mar   10

由于我需要优化,因此需要找到 3 月份没有发薪的员工并仅使用 Join

我使用子查询搜索 stmt

select E.Name from Employee where E.ID not in (Select EID from salary where month ='mar' );

出于优化目的,我被要求将其转换为加入

我尝试使用

Select E.Name from Employee E left join Salary S on E.ID = S.EID where S.EID = null;

但这不是我想要的,我只需要在3月份没有发工资的员工。

4

2 回答 2

4

试试这个:

SELECT E.Name
FROM Employee E
    LEFT JOIN salary S
        ON E.Id = S.EID
          AND S.month ='mar'
GROUP BY E.Name
HAVING COUNT(E.Id) != COUNT(S.EID)

SQL 小提琴演示

于 2013-02-27T10:45:52.250 回答
1
SELECT E.Name
FROM Employee E
    LEFT JOIN salary S
        ON E.Id = S.EID
          AND S.month ='mar'
GROUP BY E.Id
HAVING COUNT(E.Id) != COUNT(S.EID)

试试这个。

于 2013-02-27T10:58:46.560 回答