mySQL JOIN语句没有返回我想要的内容

时间:2010-11-13 21:15:50

标签: sql mysql join mysql-error-1064

我想显示两个表的“FULL JOIN”,但是使用带有外键的中介来创建匹配。

这应该显示他们正在处理的项目的所有员工的列表,并显示没有项目的任何员工或没有员工的项目。

此查询的问题是第二个“RIGHT JOIN”会覆盖第一个“LEFT JOIN”。第二次“全加入”的所有尝试都失败了。 (1064语法错误,真正的描述性)

SELECT EMP_LNAME, EMP_FNAME, Project.PROJ_NAME
FROM Employee1
LEFT JOIN Assignment ON Employee1.EMP_CODE = Assignment.EMP_CODE
FULL JOIN Project ON Assignment.PROJ_CODE = Project.PROJ_CODE
ORDER BY Employee1.EMP_LNAME /* Syntax error */

我试过的第二种类型

SELECT EMP_LNAME, EMP_FNAME, Project.PROJ_NAME
FROM Employee1
LEFT JOIN Assignment ON Employee1.EMP_CODE = Assignment.EMP_CODE
RIGHT JOIN Project ON Assignment.PROJ_CODE = Project.PROJ_CODE
ORDER BY Employee1.EMP_LNAME /* Right join overwrites original left join */

2 个答案:

答案 0 :(得分:3)

要在MySQL中获得FULL OUTER JOIN,您需要首先执行LEFT JOIN,然后执行RIGHT JOIN和UNION ALL结果(或者代替RIGHT JOIN反转表并使用另一个LEFT JOIN)。但有一点需要注意的是,在第二个连接中,您需要丢弃连接成功的行,这样就不会在结果中出现重复。

SELECT EMP_LNAME, EMP_FNAME, Project.PROJ_NAME
FROM Employee1
LEFT JOIN Assignment ON Employee1.EMP_CODE = Assignment.EMP_CODE
LEFT JOIN Project ON Assignment.PROJ_CODE = Project.PROJ_CODE
UNION ALL
SELECT EMP_LNAME, EMP_FNAME, Project.PROJ_NAME
FROM Project
LEFT JOIN Assignment ON Assignment.PROJ_CODE = Project.PROJ_CODE
LEFT JOIN Employee1 ON Employee1.EMP_CODE = Assignment.EMP_CODE
WHERE Employee1.ID IS NULL
ORDER BY EMP_LNAME

我假设你的Employee1表有一个不可为空的字段调用ID。

答案 1 :(得分:2)

MySQL doesn't support "FULL" in it's JOIN syntax,您具体称之为FULL OUTER JOIN

这是one of the means to get the output you desire

    SELECT e.emp_lname,
           e.emp_fname,
           p.project_name
      FROM EMPLOYEE e
 LEFT JOIN ASSIGNMENT a ON a.emp_code = e.emp_code
      JOIN PROJECT p ON p.proj_code = a.proj_code
UNION
   SELECT e.emp_lname,
           e.emp_fname,
           p.project_name
      FROM EMPLOYEE e
RIGHT JOIN ASSIGNMENT a ON a.emp_code = e.emp_code
      JOIN PROJECT p ON p.proj_code = a.proj_code
ORDER BY emp_lname