i have a database that has the following tables
EMPLOYEE:[FIRST_NAME, MID_INIT, LAST_NAME, SSNO, BDATE, ADDRESS, GENDER, SALARY, SUPSSNO, DNO]
DEPARTMENT:[DEPT_NAME, DEPT_NO, MGRSSNO, MGR_START_DATE]
DEPARTMENT.MGRSSNO is a foreign key of EMPLOYEE.SSNO
I need to build a query using a UNION to display the names of all employees, and if they are a dept manager, the dept_name.
Here is what i have
SELECT E.FIRST_NAME, E.LAST_NAME, E.ADDRESS, D.DEPT_NAME
FROM EMPLOYEE E, DEPARTMENT D
WHERE E.SSNO=D.MGRSSNO
UNION
SELECT E.FIRST_NAME, E.LAST_NAME, E.ADDRESS, D.DEPT_NAME
FROM EMPLOYEE E, DEPARTMENT D;
except i am getting 36 rows (9 employees x 4 departments) instead of the 9 that I should be getting.
Any help would be greatly appreciated.
Use a LEFT JOIN
, not UNION
:
SELECT e.FIRST_NAME, e.LAST_NAME, e.ADDRESS, d.DEPT_NAME
FROM EMPLOYEE e
LEFT JOIN DEPARTMENT d ON e.SSNO = d.MGRSSNO
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.