【问题标题】:"The same table " LEFT JOINE ON " the same commen field " in MS-Access 2016MS-Access 2016 中的“同一张表”LEFT JOIN ON“同一个公共字段”
【发布时间】:2020-10-10 15:47:19
【问题描述】:

我有这样的事情

员工 (Emp_ID , Emp_Name)
安全卫士(MainEmp_ID,AlternativeEmp_ID)。 // 保安被视为雇员

我的sql查询如下

  Select Employe.Emp_Name 
  From ( Employe
  LEFT JOIN ON SecurityGuards ON SecurityGuards.MainEmp_ID = Employe.Emp_ID)
  LEFT JOIN ON SecurityGuards ON SecurityGuards.AlternativeEmp_ID = Employe.Emp_ID

现在我希望查询按名称而不是 ID 显示主要和备用 Guard,但它只是给我一个错误,说“不支持连接表达式” 虽然删除第二个 LEFT Join 工作正常。 我正在使用 MS-Access 2016

【问题讨论】:

  • 帮助我们帮助您 - 请分享一些示例数据以及您尝试获得的结果

标签: sql ms-access outer-join ms-access-2016


【解决方案1】:

您必须将SecurityGuards 加入Employee 的2 个副本才能获得这2 个名称:

SELECT e1.Emp_Name AS MainName, e2.Emp_Name AS AlternativeName
FROM (SecurityGuards AS s 
LEFT JOIN Employee AS e1 ON e1.Emp_ID = s.MainEmp_ID)
LEFT JOIN Employee AS e2 ON e2.Emp_ID = s.AlternativeEmp_ID

【讨论】:

  • 通过添加员工副本,您的意思是创建一个具有相同数据的新员工表?
  • 不,不是那样的。同一个表 Employee 在查询中使用了两次,具有 2 个不同的别名 e1 和 e2,因为您必须从 Employee 中为这 2 个名称的 SecurityGuards 的每一行获取 2 个值。
  • 没有意识到select语句中的e1和e2在LEFT Join语句中有别名,谢谢大家的帮助
【解决方案2】:

如果你想要一行结果,你可以使用表别名和两个LEFT JOINs:

select  . . .
from (Employe as E left join
      SecurityGuards as sgm
      ON sgm.MainEmp_ID = e.Emp_ID
     ) left join
     SecurityGuards as sga
     ON sga.AlternativeEmp_ID = e.Emp_ID;

如果您只需要任一列中的员工,请使用EXISTS

select e.*
from employe as e
where exists (select 1
              from SecurityGuards as sg
              where e.Emp_ID in (sg.MainEmp_ID, sg.AlternativeEmp_ID
             );

【讨论】:

  • 它似乎不适合我。不知道如果我做错了什么,或者在上面的选择语句中应用@Gordon 方法会出错,因为它将 Emp_ID 与 Emp_Name 关联起来!
  • @GeboA 。 . .此查询中没有“将 [ing] EMP_ID 与 EMP_Name 相关联”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2016-04-18
  • 2023-03-08
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多