坚持写这个查询,试图使用内连接

时间:2015-11-17 06:50:38

标签: sql database select inner-join

我的数据库:

EMPLOYEE (fmane, 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)

我想获得没有孩子使用内部联接的已婚雇员的姓氏

到目前为止,我只能想出这个:

SELECT E.*
FROM Employee AS E INNER JOIN Dependent AS D
ON ( E.ssn = D.essn AND D.relationship IN ( 'husband','wife') )

无论如何想要纠正我的代码?我想使用内部联接来找到我想要的东西。

2 个答案:

答案 0 :(得分:0)

编辑:另一种不使用减号

的方法
select e.lname from
employee e inner join dependent d
on e.ssn=d.essn 
where D.relationship IN ('husband','wife')
and e.ssn not in (
    select e.ssn from
    employee e inner join dependent d
    on e.ssn=d.essn 
    where D.relationship IN ('child')
)

使用减号

SELECT e.lname
FROM Employee E 
INNER JOIN Dependent D
ON E.ssn = D.essn 
where D.relationship IN ('husband','wife')

minus

select e.lname
FROM Employee E 
INNER JOIN Dependent D
ON E.ssn = D.essn 
where D.relationship IN ('child') --or children what ever you are using

答案 1 :(得分:0)

尝试以下方法。内部查询查找只有一个受抚养人的所有员工,可能是配偶另一个家庭成员。然后我再次将此结果加入Dependent表,并限制其他家庭成员为丈夫或妻子。

SELECT e1.*
FROM Employee e1 INNER JOIN
(
    SELECT e2.ssn
    FROM Employee e2 INNER JOIN Dependent d1 ON e2.ssn = d1.essn
    GROUP BY e2.ssn
    HAVING COUNT(*) = 1
) t ON e1.ssn = t.ssn
INNER JOIN Dependent d2 ON e1.ssn = d2.essn
WHERE d2.relationship IN ('husband', 'wife')