如何创建连接两个或更多表以满足要求的视图?

时间:2019-04-05 18:58:11

标签: sql sql-server

我有一组表和一个特定的业务需求,需要通过在SQL中创建一个View来解决。我在理解连接和东西等方面遇到了麻烦。我已经尝试过,但是我认为我完全错了,需要一些帮助。

这些表格如下:

tblClients (
  ClientID, 
  ClientName, 
  ClientAddress, 
  ClientCity, 
  ClientProvince, 
  ClientPostalCode, 
  ClientPhone, 
  ClientEmail
)

tblVehicle (
  VehicleID, 
  VehicleMake, 
  VehicleModel, 
  VehicleYear, 
  ClientID
)

tblEmployees (
  EmployeeID, 
  EmployeeFirstName, 
  EmployeeLastName, 
  EmployeeAddress, 
  EmployeeCity, 
  EmployeeProvince, 
  EmployeePostalCode, 
  EmployeePhone, 
  EmployeeEmail
)

tblWorkOrders (
  OrderID, 
  VehicleID, 
  EmployeeID, 
  WorkDescription, 
  PartsCost, 
  LabourCost, 
  IssueDate, 
  CompletionDate
)

和要求是这样的

正在考虑使用一个Web应用程序,该应用程序将允许具有帐户的客户(使用其电子邮件地址作为登录名)使用车库查看其发票/工单历史记录。 使用SQL创建一个视图,该视图将使客户能够看到他们在每辆车上完成的工作,包括工作描述,成本和日期,但看不到哪个员工完成了工作。


我这么远:

CREATE VIEW WORK_HISTORY AS
SELECT TBLWORKORDERS.WORKDESCRIPTION,                    
       TBLWORKORDERS.PARTSCOST, TBLWORKORDERS.LABOURCOST,                         
       TBLWORKORDERS.ISSUEDATE,TBLWORKORDERS.COMPLETIONDATE
       TBLVEHICLES.VEHICLEMAKE, TBLVEHICLES.VEHICLEMODEL, 
       TBLVEHICLES.VEHICLEYEAR
  FROM TBLWORKORDERS 
  INNER JOIN TBLVEHICLE
  ON TBLWORKORDERS.VEHICLEID = TBLVEHICLE.VEHICLEID

我认为它并不复杂,但是我对SQL还是陌生的,因此,感谢您的所有帮助和批评。如果您还有其他需要,请告诉我,我们会根据需要进行编辑。谢谢!

更新:我认为这是一个内部联接。

1 个答案:

答案 0 :(得分:0)

请参见下文,如何将表连接在一起,以便从“客户表”链接到客户希望为其车辆查看的工单。

/* First Requirement: Filter aka WHERE Clause 
 | The requirement states the Client logs in using their email address.
*/
SELECT *
FROM tblClients c
WHERE c.ClientEmail = 'email@fakeEmail.com'
;

/* Let's expand on this now that we have found the Client by email
 | NEXT Requirement is to find the Invoice/Work Order.
 |   Ask yourself: How do I get from the Clients table to the Work Order Table?
 | I see that the Work Order Table does NOT contain a ClientID.
 |   I see however that it DOES contain a VehicleID and the Vechicle Table has a ClientID.
 | Perfect... I can now get from the Client table to the Work Order table using the Vehicle Table.
*/

SELECT c.ClientName, c.ClientEmail
  , v.VehicleModel
  , wo.WorkDescription, wo.PartsCost, wo.IssueDate, wo.CompletionDate
FROM tblClients c
  /* Tie Clients to their vehicle */
  JOIN tblVehicle v ON v.ClientID = c.ClientID
  /* Now Tie the Vehicle to the Work Orders */
  JOIN tblWorkOrders wo ON wo.VehicleID = v.VehicleID
WHERE /* Add email filter so we can see a specific client.  No filter means see ALL */
  c.ClientEmail = 'email@fakeEmail.com'
;

关于创建视图...,在这种情况下,您将不包括WHERE子句,但您需要包括电子邮件地址,以便在调用视图时可以使用它。

CREATE VIEW WORK_HISTORY AS
SELECT c.ClientName, c.ClientEmail
  , v.VehicleModel
  , wo.WorkDescription, wo.PartsCost, wo.IssueDate, wo.CompletionDate
FROM tblClients c
  /* Tie Clients to their vehicle */
  JOIN tblVehicle v ON v.ClientID = c.ClientID
  /* Now Tie the Vehicle to the Work Orders */
  JOIN tblWorkOrders wo ON wo.VehicleID = v.VehicleID
;