简体   繁体   中英

SQL query using joins for one to many table having a where condition

I am looking for query using joins to find, list of departments which have all employees having age less than 30, In the below example the result i am looking for is ' Computers ' as all the employees are having less then 30 age

Department table:

Id  | Department Name 
100 | Computers
101 | Electronics
102 | Mechanical

Employee table

Id  | DepartmentId | Employee Name | Age
901 | 100          | Sam           | 25
902 | 100          | Ram           | 28
903 | 101          | Joe           | 35
904 | 101          | Kate          | 27

You can use not exists :

select d.id, d.department_name
from department d
where not exists (
    select 1
    from employee e
    where e.department_id = d.id and e.age >= 30
)

The same logic can be phrased with a left join antipattern:

select d.id, d.department_name
from department d
left join employee e on e.department_id = d.id and e.age >= 30
where e.id is null

With this query:

select departmentid
from employee
group by departmentid
having max(age) < 30

you get all the departmentid s with employees aged < 30.
So use it like this:

select * from departments
where id in (
  select departmentid
  from employee
  group by departmentid
  having max(age) < 30
)

A join is not the most natural way to write such a query. not exists is:

select d.*
from departments d
where not exists (select 1
                  from employees e
                  where e.DepartmentId = d.id and e.age >= 30
                 );

A simple way to turn this into a join is:

select d.*
from departments d left join
     employees e
     on e.DepartmentId = d.id and e.age >= 30
where e.id is null;  -- no matches
select departmentid
from employee e
   inner join department d on d.Id = e.departmentId
group by e.departmentid —- all columns from Department which are needed
having max(e.age) < 30

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