查询内连接两个表

时间:2016-09-03 09:22:33

标签: mysql

下面我创建了三个表:

CREATE TABLE EMPLOYEE(
    EMPLOYEE_ID [int] identity (1,1) not null,
    FIRSTNAME [nvarchar] (20) not null,
    LASTNAME [nvarchar] (20) not null, 
);

CREATE TABLE LEAVE(
    LEAVE_ID [int] identity (1,1) not null,
    START_DATE [DATE]  not null,
    END_DATE [DATE]  not null,
);

CREATE TABLE EMPLOYEE_LEAVE(
    ELEAVE_ID [int] identity (1,1) not null,
    LEAVE_ID [int] not null,
    EMPLOYEE_ID [int] not null,
);

我正在尝试创建一个显示所有员工离开日期的查询。

CREATE VIEW [VW_CURRENT_LEAVE]
AS
SELECT E.EMPLOYEE_ID, 
    E.FIRSTNAME, 
    E.LASTNAME, 
    L.START_DATE, 
    L.END_DATE
FROM EMPLOYEE E, 
    LEAVE L, 
    EMPLOYEE_LEAVE EL
WHERE   E.EMPLOYEE_ID = EL.E.EMPLOYEE_ID
AND EL.LEAVE_ID = L.LEAVE_ID
AND L.END_DATE >= GETDATE()
AND L.START_DATE <= GETDATE()

GO

但是查询只返回null。标题是我想要的,但是为什么它没有填写信息呢?

1 个答案:

答案 0 :(得分:0)

首先,您应该删除FROM子句中的逗号。自ANSI-92标准以来,这种表连接方式已被正式弃用,原因包括它甚至难以弄清楚实际的连接标准是什么。

尝试此查询:

SELECT E.EMPLOYEE_ID,
       E.FIRSTNAME,
       E.LASTNAME,
       L.START_DATE,
       L.END_DATE
FROM EMPLOYEE E
INNER JOIN EMPLOYEE_LEAVE EL
    ON E.EMPLOYEE_ID = EL.EMPLOYEE_ID
INNER JOIN LEAVE L
    ON EL.LEAVE_ID = L.LEAVE_ID

查看返回的内容,如果看起来不错,可以尝试添加以下WHERE子句:

WHERE L.END_DATE >= GETDATE() AND
      L.START_DATE <= GETDATE()

如果添加WHERE子句导致没有返回记录,则应检查以确保所有员工都安排了有效的休假。