选择一个表中存在但另一个表中缺少的值的最佳方法是什么? ORACLE

时间:2017-03-05 20:34:57

标签: sql oracle

我的解决方案:
表名:HW1_PERSON,hw1_sfaff

SELECT I.ID,person.person_id
FROM HW1_PERSON
LEFT JOIN HW1_STAFF
ON     
I.ID=person.person_id
WHERE person.person_id IS NULL;  
  

第5行的错误:ORA-00904:“PERSON”。“PERSONID”:标识符无效

数据示例:

INSERT INTO hw1_person (id, first_name, last_name, dob, address) VALUES (26, 'fname44', 'lname44', to_date('2/12/1990', 'MM/DD/YYYY'), '301 6th Av NJ');
INSERT INTO hw1_person (id, first_name, last_name, dob, address) VALUES (27, 'fname45', 'lname45', to_date('12/8/1982', 'MM/DD/YYYY'), '975 7th Av NJ');

INSERT INTO hw1_staff (person_id, emp_num, start_date, end_date, salary) VALUES (1, 'WZIAE', to_date('7/1/1965', 'MM/DD/YYYY'), null,70000);
INSERT INTO hw1_staff (person_id, emp_num, start_date, end_date, salary) VALUES (2, 'EWEMU', to_date('11/18/1980', 'MM/DD/YYYY'), to_date('12/26/1970', 'MM/DD/YYYY'),80000);
INSERT INTO hw1_staff (person_id, emp_num, start_date, end_date, salary) VALUES (3, 'KJHSN', to_date('2/26/1991', 'MM/DD/YYYY'), null,40000);                                          

2 个答案:

答案 0 :(得分:1)

您可以使用NOT EXISTS

select *
from hw1_staff s
where not exists (
        select 1
        from hw1_person p
        where p.id = s.person_id
        )

它将从员工中选择所有不在人员表中的相应行的行。

或许你想要相反的,即所有非工作人员:

select *
from hw1_person p
where not exists (
        select 1
        from hw1_staff s
        where p.id = s.person_id
        )

如果您想使用基于JOIN的替代方案来获取非工作人员:

select *
from hw1_person p
left join hw1_staff s
    on p.id = s.person_id
where s.person_id is null

答案 1 :(得分:0)

你在查询中犯了错误。

您写道:

FROM HW1_PERSON
LEFT JOIN HW1_STAFF

但要使您的查询有效,必须是:

FROM HW1_PERSON I
LEFT JOIN HW1_STAFF person

正如其他答案所述;是的,您可以使用NOT EXISTS来完成任务。