简体   繁体   中英

Converting SubQuery to Join

I have 2 Tables Employee and salary Employe => ID, Name Fields

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

Need to find the Employees who have not got salary in month of march and Using Join only since I need optimization

I have search stmt using sub query as

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

for optimization purposed I was asked to convert this to join

I tried using

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

But this is not what I desired I need only employees who was not given salary in month of March Only.

Try this:

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 FIDDLE DEMO

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)

try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM