如何简化where子句中的嵌套选择?

时间:2017-03-09 19:22:04

标签: sql database oracle oracle11g

我有4个表EMPLOYEECOMPANYWORKSMANAGES。表格定义如下 -

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)));

它工作正常。但我想知道有没有更简单的方法来进行此查询?

4 个答案:

答案 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
  • 来处理这种情况
  • 名称是用于外键关系的非常糟糕的键。通常数字ID更好。如果员工或公司更改名称会怎样?
  • 表别名使查询更容易编写和阅读。

答案 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