对表“mdl_user”的FROM子句条目的引用无效

时间:2015-03-06 21:08:06

标签: sql postgresql join left-join moodle

我正在尝试为Moodle v2.7数据库(使用PostgreSQL 9.3)的特定课程构建所有用户及其分数的报告。我收到以下错误并查看了问题和其他示例产生相同的错误,但没有一个能为我的具体问题提供答案。不确定我在这里忽略了什么。

  

错误:对表" mdl_user"

的FROM子句条目的引用无效
SELECT 
    mdl_user.lastname as LastName,
    mdl_user.firstname as FirstName,
    Grr.finalgrade as Grade,
    REPLACE(Grr.itemname,'COURSE: ','') as Course,
    TO_CHAR(TO_TIMESTAMP(Grr.timemodified), 'MM/DD/YYYY') as Completed
FROM
    public.mdl_user LEFT JOIN (
        SELECT 
            mdl_grade_grades.finalgrade,
            mdl_grade_items.itemname,
            mdl_grade_grades.userid,
            mdl_grade_grades.timemodified
        FROM
            public.mdl_grade_items LEFT JOIN public.mdl_grade_grades
                ON public.mdl_grade_items.id = public.mdl_grade_grades.itemid
        WHERE
            mdl_grade_grades.userid = mdl_user.id AND
            mdl_grade_items.itemname LIKE 'COURSE: Lock Out Tag Out: ECP'
    ) AS Grr ON Grr.userid = public.mdl_user.id
ORDER BY
    mdl_user.lastname,
    mdl_user.firstname

2 个答案:

答案 0 :(得分:4)

@avk是对的。但还有更多。适当简化的查询:

SELECT u.lastname
     , u.firstname
     , g.finalgrade AS grade
     , right(i.itemname, -8) AS course
     , to_char(to_timestamp(g.timemodified), 'MM/DD/YYYY') AS completed
FROM   public.mdl_user         u
LEFT   JOIN
      (public.mdl_grade_items  i
  JOIN public.mdl_grade_grades g ON g.itemid = i.id
                                AND i.itemname = 'COURSE: Lock Out Tag Out: ECP'
      ) ON g.userid = u.id
ORDER  BY 1,2;

答案 1 :(得分:1)

在子选择Grr中,删除mdl_grade_grades.userid = mdl_user.id 这导致错误,无论如何它已经加入AS Grr ON Grr.user.id=public.mdl_user.id行。