使用联接信息从表中获取信息

时间:2018-11-14 06:27:20

标签: sql

我是SQL的新手。我正在学习联接查询,以便使用信息从表中查找信息。我正在研究这个问题。

获取雇员的雇员编号以及他们在任何给定部门上任的日期。

下面是我的表定义:

CREATE TABLE Employees (
    EmployeeID      int         IDENTITY(1,1) PRIMARY KEY
    ,EmployeeNumber int         UNIQUE
    ,DateOfBirth    datetime        NOT NULL
    ,FirstName      nvarchar(14)    NOT NULL
    ,MiddleName     nvarchar(14)    NOT NULL
    ,LastName       nvarchar(16)    NOT NULL
    ,DateHired      datetime        NOT NULL 
)

CREATE TABLE Customers (
    CustomerID      int         IDENTITY(1,1) PRIMARY KEY
    ,FirstName      nvarchar(14)    NOT NULL
    ,MiddleName     nvarchar(14)    NOT NULL
    ,LastName       nvarchar(16)    NOT NULL
    ,DateLastVisited datetime       NOT NULL 
    ,EmailAddress   nvarchar(52)    NOT NULL
)

CREATE TABLE Departments (
    DepartmentID    int         IDENTITY(1,1) PRIMARY KEY
    ,Code           nchar(4)        UNIQUE
    ,Name           nvarchar(40)    NOT NULL 
)

CREATE TABLE DepartmentEmployees (
    DepartmentEmployeeID    int     IDENTITY(1,1) PRIMARY KEY
    ,EmployeeID     int             NOT NULL
            CONSTRAINT Department_Employee REFERENCES Employees(EmployeeID)
    ,DepartmentID   int         NOT NULL
            CONSTRAINT Employee_Department REFERENCES Departments(DepartmentID)
    ,DateStarted    datetime        NOT NULL
    ,DateEnded      datetime        NOT NULL 
)

CREATE TABLE Salaries (
    SalaryID        int         IDENTITY(1,1) PRIMARY KEY
    ,EmployeeID     int         NOT NULL
            CONSTRAINT Salaried_Employee REFERENCES Employees(EmployeeID)
    ,Amount     money           NOT NULL
    ,DateStarts     datetime        NOT NULL
    ,DateEnds       datetime        NOT NULL 
)

我通过将数据相应地插入表中来添加信息。 对于这个问题。 我已经写了这个答案,但是我不确定它是否正确。

  SELECT e.EmployeeNumber, 
         d.DateStarted 
    FROM Employees e
    Right 
     Join DepartmentEmployees d
       on e.EmployeeID= d.DepartmentEmployeeID;

1 个答案:

答案 0 :(得分:0)

DepartmentEmployeeID是表部门的主键,您需要在两个表中都加入雇员ID。

SELECT E.EmployeeNumber, D.DateStarted 
FROM DepartmentEmployees D 
LEFT JOIN Employees E 
ON E.EmployeeID= D.EmployeeID;