查询错误(1066) - MySQL

时间:2014-09-24 10:55:05

标签: mysql moodle

当我在MySQL 5.5.3下执行此查询时,我遇到了一些问题。它在查询中返回错误(1066):不唯一的表/别名:'categories'

SELECT COUNT(DISTINCT lra.userid) AS learners, COUNT(DISTINCT tra.userid) AS teachers
FROM mdl_course AS courses, mdl_course_categories AS categories
LEFT JOIN mdl_context AS ctx ON c.id = ctx.instanceid
JOIN mdl_role_assignments  AS lra ON lra.contextid = ctx.id
JOIN mdl_role_assignments  AS tra ON tra.contextid = ctx.id
JOIN mdl_course_categories AS categories ON courses.category = categories.id
WHERE courses.category = categories.id
AND (
    categories.path LIKE '%/9/%' 
    OR categories.path LIKE '%/9'
    )
AND lra.roleid=5
AND tra.roleid=3

我有点不知所措,因为我把列和表名混淆了。谁能找到我可能出错的地方?

2 个答案:

答案 0 :(得分:1)

您有一个选择语句

FROM mdl_course AS courses, mdl_course_categories AS categories

然后

JOIN mdl_course_categories AS categories ON courses.category = categories.id

这使它成为非唯一别名

您应该删除选择部分,并且应该是

SELECT COUNT(DISTINCT lra.userid) AS learners, COUNT(DISTINCT tra.userid) AS teachers
FROM mdl_course AS courses
LEFT JOIN mdl_context AS ctx ON c.id = ctx.instanceid
JOIN mdl_role_assignments  AS lra ON lra.contextid = ctx.id
JOIN mdl_role_assignments  AS tra ON tra.contextid = ctx.id
JOIN mdl_course_categories AS categories ON courses.category = categories.id

答案 1 :(得分:0)

在第二行查询中,您使用了表名,在第6行中,您再次使用了该表。 如

FROM mdl_course AS courses, mdl_course_categories AS categories

并且

JOIN mdl_course_categories AS categories ON courses.category = categories.id