左外加入sql查询

时间:2015-11-17 22:34:38

标签: mysql sql database group-by outer-join

数据库:

EMPLOYEE (fname, minit, lname, ssn, birthdate, address, sex, salary, superssn, dno)     KEY: ssn
DEPARTMENT (dname, dnumber, mgrssn, mgrstartdate)               KEY: dnumber.
PROJECT  (pname, pnumber, plocation, dnum)                          KEY: pnumber.
WORKS_ON (essn, pno, hours)                                         KEY: (essn, pno)
DEPENDENT  (essn, dependent-name, sex, bdate, relationship)             KEY: (essn, dependent-name)

我想使用left outer joingroup by来... ... 查找在3个或更多项目中工作且不在克利夫兰市的经理的姓氏和SSN。

这是我到目前为止所做的:

select Lname
  from Employee e outer join Department d
where (e.ssn = d.mgrssn) 
   and  ssn NOT in (
                      select  w.essn
                       from   works_on w outer join Project p
                      where w.pno = p.pnumber
                          and  p.plocation = 'Cleveland'
                      group by w.essn
                      having count(*) >= 3
                     )

我是否使用left outer joingroup by做到了?我应该将此代码分为两部分,例如循环吗?

1 个答案:

答案 0 :(得分:1)

选择JOIN查找员工的所有项目

首先HAVING告诉您此用户在'Cleveland'

中没有项目

第二个HAVING告诉您此用户有3个项目或更多

SELECT e.Lname, e.ssn
FROM Employee e   
JOIN works_on w
  ON e.ssn = w.essn
JOIN Project p
  ON w.pno = p.pnumber
GROUP BY e.ssn
HAVING 
     SUM(CASE WHEN p.plocation = 'Cleveland' THEN 1 ELSE 0 END) = 0
AND  COUNT(*) >= 3