문제

I'm a student entering the world of SQL for the first time and I cannot find any clear and understandable documentation on how to use to_somedatatype(null) to substitute for missing columns in a UNION, INTERSECT, etc. I'm using the HR schema that comes build in with Oracle Database for my first few projects and the following query works (I get a list of the employee_id numbers for only those employees with dependents):

SELECT employee_id "Employees with Dependents"
FROM employees
INTERSECT
SELECT relative_id
FROM dependents;

However, as soon as I want to include the names of the employees and dependent birth dates, I'm stuck. This variation perform an error-free search but yields no results (outputs "no rows selected"):

SELECT e.employee_id "Employees with Dependents",
  e.first_name,
  e.last_name,
  to_date(NULL) "Dependent Birthdate"
FROM employees e
INTERSECT
SELECT d.relative_id,
  TO_CHAR(NULL),
  TO_CHAR(NULL),
  d.birthdate
FROM dependents d;

Several variations replacing to_date with to_number or just plain null and to_char with to_varchar2 or null fail to produce any rows.

What I'd like to produce is a single row for each dependent which displays the guardian's employee number, first name, last name, and the birth date of the dependent. I'm confident that my problem is the use of these null placeholders, combined with limited understanding of set operators in general. (My understanding is that, when I used a null placeholder like to_date(null), it will not be included in the comparison since there's nothing there to be compared to.)

Can someone please explain to me how to properly use these placeholders?

도움이 되었습니까?

해결책 2

The reason your queries don't work is that you have no NULL values in the corresponding fields. You are using INTERSECT. Actually, you want to join the tables together, something like:

SELECT e.employee_id "Employees with Dependents",
  e.first_name,
  e.last_name,
  d.birthdate "Dependent Birthdate"
FROM employees e join
     dependents d
     on d.relative_id = e.employee_id

다른 팁

You must match the data type (using the TO_CHAR function or any other conversion functions) when columns do not exist in one or the other table. for example:

SELECT location_id, department_name "Department", TO_CHAR(NULL) "Warehouse location" FROM departments UNION SELECT location_id, TO_CHAR(NULL) "Department", state_province FROM locations;

let you relate with your scenario

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top