gpt4 book ai didi

sql - 如何简化 where 子句中的嵌套 select?

转载 作者:太空狗 更新时间:2023-10-30 01:59:09 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用显式内部连接而不是嵌套子选择

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

关于sql - 如何简化 where 子句中的嵌套 select?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42703768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com