我可以使用INNER JOIN替换WHERE吗?

时间:2012-11-14 02:12:10

标签: sql database ms-access inner-join where

我有三张桌子。员工,项目(多对多)和员工项目。

我想检索每个员工的姓名及其各自的项目。

我试图使用此查询:

SELECT Employee.name, Project.name 
FROM Employee, Project
INNER JOIN EmployeeProject ON Employee.empNo = EmployeeProject.empNo
INNER JOIN EmployeeProject ON Project.projectNo = EmployeeProject.projectNo;

Access给了我一个语法错误。然后我尝试了这个查询并且它有效:

SELECT Employee.name, Project.name 
FROM Employee, Project, EmployeeProject
WHERE Employee.empNo = EmployeeProject.empNo AND EmployeeProject.projectNo = Project.projectNo;

我的问题是;可以使用WHERE来链接表,或者有更好的方法来实现它,比如INNER ......

此致

2 个答案:

答案 0 :(得分:5)

使用显式JOIN时,不会在FROM子句中使用逗号分隔表。显式JOIN的正确语法(优先于使用WHERE子句的旧隐式语法)是:

SELECT
  /* Probably will need to give these aliases since the're both called name */
  Employee.name AS empname,
  Project.name AS projname 
FROM 
  Employee
  /* Employee joins through EmployeeProject */
  INNER JOIN EmployeeProject ON Employee.empNo = EmployeeProject.empNo
  /* ...into Project */
  INNER JOIN Project ON Project.projectNo = EmployeeProject.projectNo;

如果Access抱怨,可能需要围绕join子句()(虽然我找不到指定它的文档)

FROM 
  (Employee
  INNER JOIN EmployeeProject ON Employee.empNo = EmployeeProject.empNo)
  INNER JOIN Project ON Project.projectNo = EmployeeProject.projectNo;

答案 1 :(得分:5)

  1. 当您涉及的表格超过2个时,即使在Access 2010中,也需要 ARE
  2. JOIN中表格的顺序是重要。你无法从员工跳转 - >项目(无关)到EmployeeProject(加入两者)
  3. 这可行

    SELECT Employee.name, Project.name 
    FROM ((Employee
    INNER JOIN EmployeeProject ON Employee.empNo = EmployeeProject.empNo)
    INNER JOIN Project ON EmployeeProject.projectNo = Project.projectNo);
    

    注意:您可以将外部括号放在FROM和最终;之间,但更安全的做法是始终包含它。

    可以嵌套连接 - 如果你像这样嵌套它们,保留表的顺序(Employee,Project,EmployeeProject):

    SELECT Employee.name, Project.name 
    FROM Employee
    INNER JOIN (Project 
                INNER JOIN EmployeeProject 
                  ON EmployeeProject.projectNo = Project.projectNo)
      ON Employee.empNo = EmployeeProject.empNo;
    

    <小时/> 使用显式JOIN语法要灵活得多,因为现在您可以显示员工,即使他们没有任何项目 - 只需更改为 LEFT 加入。

    SELECT Employee.name, Project.name 
    FROM ((Employee
    LEFT JOIN EmployeeProject ON Employee.empNo = EmployeeProject.empNo)
    LEFT JOIN Project ON EmployeeProject.projectNo = Project.projectNo);
    

    注意:在数据表视图和表单中,生成的列名为“Employee.name”和“Project.name”,因此您不必显式别名,尽管它可能有用。