简体   繁体   English

查询内部联接两个表

[英]Query to inner join two tables

Below I have created three tables: 下面,我创建了三个表:

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

I'm trying to create a query that shows all the employees leave dates. 我正在尝试创建一个查询,以显示所有员工的离职日期。

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

But the query just returns everything as null. 但是查询只是将所有内容返回为null。 The titles are as I want them but how come it's not filling the information? 标题是我想要的,但是为什么没有填写这些信息?

First of all, you should get rid of those commas in the FROM clause. 首先,您应该在FROM子句中删除那些逗号。 This style of table join has been officially deprecated since the ANSI-92 standard, for reasons including that it makes it difficult to even figure out what the actual join criteria is. 自ANSI-92标准以来,这种表连接样式已被正式弃用,原因包括它使得甚至很难弄清实际的连接标准是什么。

Try this query: 试试这个查询:

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

See what this returns, and if it looks good you can try adding the following WHERE clause: 看看返回的结果,如果看起来不错,您可以尝试添加以下WHERE子句:

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

If adding the WHERE clause causes no records to be returned you should check to makes sure that any employees have active leave scheduled. 如果添加WHERE子句导致不返回任何记录,则应检查以确保安排了所有员工的活动假期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM