简体   繁体   English

Oracle SQL案例,比较不同表和联接中的列

[英]Oracle SQL Cases, Comparing Columns in Different Tables and Joins

Instructions: 说明:

  • Select columns EName and VehicleName 选择列ENameVehicleName
  • If EName doesn't own a vehicle, display Null as VehicleName . 如果EName不拥有车辆,则显示Null作为VehicleName

Relevant SQL tables and columns: 相关的SQL表和列:

Table         | Columns
--------------+-------------------------
Emp           | EmpNo, EName
Vehicle       | VehicleId, VehicleName
EmpVehicle    | EmpNo, VehicleId

My current attempt is: 我目前的尝试是:

SELECT Emp.EName, Vehicle.VehicleName
FROM Emp
INNER JOIN EmpVehicle ON Emp.EmpNo = EmpVehicle.EmpNo
INNER JOIN Vehicle ON EmpVehicle.VehicleId = Vehicle.VehicleId

The above query works in the sense that it displays all employee names with a EmpVehicle.VehicleId and Vehicle.VehicleName entry but I have no clue how to include employee names that don't have a vehicle with joins involved. 上面的查询在某种意义上起作用,它显示所有员工姓名带有EmpVehicle.VehicleIdVehicle.VehicleName条目,但我不知道如何包含没有涉及联接的车辆的员工姓名。

I have been able to determine that not all EmpNo values in the Emp.EmpNo column are in the EmpVehicle.EmpNo column and that my above query only displays the names of employees whose employee number are in the EmpVehicle.EmpNo column. 我已经能够确定并非Emp.EmpNo列中的所有EmpNo值都在EmpVehicle.EmpNo列中,并且我的上述查询仅显示其员工编号在EmpVehicle.EmpNo列中的员工的EmpVehicle.EmpNo

How would you write a case that looks at if an employee number in column Emp.EmpNo is not in column EmpVehicle.EmpNo and if it is not return Null in the displayed VehicleName ? 您如何编写一个案例,查看Emp.EmpNo列中的员工编号是否不在EmpVehicle.EmpNo列中,并且在显示的VehicleName是否返回Null?

You should LEFT JOIN to keep data from your Emp table that doesn't match on your INNER JOIN : 你应该LEFT JOIN来保持你的Emp表中与INNER JOIN不匹配的数据:

SELECT Emp.EName, Vehicle.VehicleName
FROM Emp
LEFT JOIN EmpVehicle
ON Emp.EmpNo = EmpVehicle.EmpNo
LEFT JOIN Vehicle
ON EmpVehicle.VehicleId = Vehicle.VehicleId

You can use left join so you can see the emp that don't have vehicle 您可以使用左连接,这样您就可以看到没有车辆的emp

SELECT Emp.EName, Vehicle.VehicleName
FROM Emp
LEFT  JOIN EmpVehicle ON Emp.EmpNo = EmpVehicle.EmpNo
LEFT  JOIN Vehicle
ON EmpVehicle.VehicleId = Vehicle.VehicleId

And check for EmpVehicle.EmpNo is null for select the emp.EName that don't have vehicle 并选中EmpVehicle.EmpNo为null以选择没有车辆的emp.EName

SELECT Emp.EName 
FROM Emp
LEFT  JOIN EmpVehicle ON Emp.EmpNo = EmpVehicle.EmpNo
WHERE EmpVehicle.EmpNo is null 

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

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