使用嵌套查询进行自我联接

时间:2019-05-11 07:41:45

标签: mysql

大家好,如果可能的话,如何对子查询进行自我联接?

这是我的尝试

SELECT *
    FROM EMPLOYEE
    INNER JOIN
    (SELECT FIRST_NAME, LAST_NAME AS FULLNAME
    FROM EMPLOYEE
    WHERE FIRST_NAME = 'Nancy' AND LAST_NAME = 'Davolio') AS FNAME
    ON EMPLOYEE.FIRST_NAME = .FIRST_NAME AND EMPLOYEE.LAST_NAME = EMPLOYEEE.FULLNAME; 

这是我自己引用的数据库

CREATE TABLE EMPLOYEE
(
    EMPLOYEE_ID     DECIMAL(9)  NOT NULL,
    LASTNAME        VARCHAR(20)     NOT NULL,
    FIRSTNAME       VARCHAR(10)     NOT NULL,
    TITLE       VARCHAR(30),
    TITLE_OF_COURTESY   VARCHAR(25),
    BIRTHDATE       DATE,
    HIREDATE        DATE,
    ADDRESS         VARCHAR(60),
    CITY        VARCHAR(15),
    REGION      VARCHAR(15),
    POSTAL_CODE     VARCHAR(10),
    COUNTRY         VARCHAR(15),
    HOME_PHONE      VARCHAR(24),
    EXTENSION       VARCHAR(4),
    PHOTO       VARCHAR(255),
    NOTES       VARCHAR(2000),
    REPORTS_TO      DECIMAL(9),
    CONSTRAINT PK_EMPLOYEE PRIMARY KEY (EMPLOYEE_ID)
);

如果工作正常,该查询应该能够找到员工报告给谁的名字和姓氏

我已经使用一个简单的自连接进行了类似的查询

 SELECT B.FIRSTNAME, B.LASTNAME
FROM EMPLOYEE AS A,
    EMPLOYEE AS B
WHERE A.REPORTS_TO = B.EMPLOYEE_ID  AND A.FIRSTNAME = 'Nancy' AND A.LASTNAME = 'Davolio';

但是,如前所述,这次我需要做同样的事情,但是在子查询上使用Selfjoin

谢谢大家的时间。

1 个答案:

答案 0 :(得分:0)

子查询应选择REPORTS_TO,而不是雇员的姓名。

SELECT e.*
FROM EMPLOYEE AS e
JOIN (
    SELECT REPORTS_TO
    FROM EMPLOYEE
    WHERE FIRSTNAME = 'Nancy' AND LASTNAME = 'Davolio') AS f
ON e.EMPLOYEE_ID = f.REPORTS_TO

DEMO