我有4个表EMPLOYEE
,COMPANY
,WORKS
和MANAGES
。表格定义如下 -
CREATE TABLE EMPLOYEE
(
EMPLOYEE_NAME VARCHAR2(50) NOT NULL PRIMARY KEY,
STREET VARCHAR2(50) NOT NULL,
CITY VARCHAR2(30) NOT NULL
);
CREATE TABLE COMPANY
(
COMPANY_NAME VARCHAR2(100) NOT NULL PRIMARY KEY,
CITY VARCHAR2(50) NOT NULL
);
CREATE TABLE WORKS
(
EMPLOYEE_NAME VARCHAR2(50) NOT NULL PRIMARY KEY REFERENCES EMPLOYEE(EMPLOYEE_NAME),
COMPANY_NAME VARCHAR2(100) NOT NULL REFERENCES COMPANY(COMPANY_NAME),
SALARY NUMBER(12,2) NOT NULL
);
CREATE TABLE MANAGES
(
EMPLOYEE_NAME VARCHAR2(50) NOT NULL PRIMARY KEY REFERENCES EMPLOYEE(EMPLOYEE_NAME),
MANAGER_NAME VARCHAR2(50) NOT NULL
);
我需要找到与他们工作的公司住在同一个城市的所有员工。 到目前为止,我已经做到了这一点。
SELECT EMPLOYEE_NAME AS Names
FROM EMPLOYEE
WHERE CITY = (SELECT CITY
FROM COMPANY
WHERE (COMPANY_NAME = (SELECT COMPANY_NAME
FROM WORKS
WHERE WORKS.EMPLOYEE_NAME = EMPLOYEE.EMPLOYEE_NAME)));
它工作正常。但我想知道有没有更简单的方法来进行此查询?
答案 0 :(得分:4)
SELECT EMPLOYEE.EMPLOYEE_NAME As Names
FROM EMPLOYEE
INNER JOIN WORKS ON WORKS.EMPLOYEE_NAME = EMPLOYEE.EMPLOYEE_NAME
INNER JOIN COMPANY ON COMPANY.COMPANY_NAME = WORKS.COMPANY_NAME
WHERE COMPANY.CITY = EMPLOYEE.CITY
这基本上是Ken White建议使用内部联接。
答案 1 :(得分:3)
您可以使用显式内连接而不是嵌套子选择
SELECT EMPLOYEE.EMPLOYEE_NAME AS Names
FROM EMPLOYEE
INNER JOIN WORKS ON WORKS.EMPLOYEE_NAME = EMPLOYEE.EMPLOYEE_NAME
INNER JOIN COMPANY ON EMPLOYEE.CITY = COMPANY.CITY
答案 2 :(得分:2)
你提到WHERE
条款,你可以这样做:
SELECT e.EMPLOYEE_NAME As Names
FROM EMPLOYEE e
WHERE e.CITY = (SELECT c.CITY
FROM Company c JOIN
Works w
ON c.COMPANY_NAME = w.COMPANY_NAME
WHERE w.EMPLOYEE_NAME = e.EMPLOYEE_NAME
);
注意:
=
更改为IN
。答案 3 :(得分:1)
select employee.employee_name
from company, employee, works
where company.company_name=works.company_name
and works.employee_name=employee.employee_name
and employee.city = company.city