简体   繁体   English

无法在 SQL Server 中绑定多部分标识符并混淆

[英]The multi-part identifier could not be bound in SQL Server and it confused

I have this SQL query:我有这个 SQL 查询:

SELECT 
    stu.sno, sname, cname
FROM
    sc scc,
    (SELECT AVG(sc.grade) AS avg_grade 
     FROM sc 
     GROUP BY sc.cno) AS avg_grades
INNER JOIN 
    course c ON c.cno = scc.cno
INNER JOIN 
    s stu ON stu.sno = scc.sno;

And there is an error that the multi-part identifier scc.cno could not be bound.并且出现无法绑定多部分标识符scc.cno的错误。 I'm confused - could someone help me?我很困惑 - 有人可以帮助我吗?

Don't mix implicit and explicit joins!不要混合隐式和显式连接! Matter of fact, don't use implicit joins: this is archaic syntax, that should not appear in new code.事实上,不要使用隐式连接:这是过时的语法,不应出现在新代码中。

The comma in the FROM clause should (probably) be a CROSS JOIN : FROM子句中的逗号应该(可能)是一个CROSS JOIN

SELECT stu.sno, sname, cname
FROM sc scc
CROSS JOIN (SELECT AVG(sc.grade) AS avg_grade FROM sc GROUP BY sc.cno) AS avg_grades
INNER JOIN course c on c.cno = scc.cno
INNER JOIN s stu on stu.sno = scc.sno;

Note that, for this subquery to be useful, you would probably need to select column avg_grade .请注意,要使此子查询有用,您可能需要selectavg_grade I would also recommend prefixing each column with the table it belongs to, to remove any possible ambiguity.我还建议在每一列前面加上它所属的表,以消除任何可能的歧义。

Finally: you (probably) can use window functions instead of a subquery:最后:您(可能)可以使用窗口函数而不是子查询:

SELECT stu.sno, sname, cname, scc.
FROM (SELECT *, AVG(grade) OVER() avg_grade FROM sc) scc
INNER JOIN course c on c.cno = scc.cno
INNER JOIN s stu on stu.sno = scc.sno;

Assuming a one-to-many join of students and courses and joined table of student courses (ie, sc ), consider a simplified aggregation on joined tables.假设学生课程的一对多联接以及学生课程的联接表(即sc ),请考虑联接表的简化聚合。 Be sure to always qualify columns with alias if query contains more than on table:如果查询包含多个表,请确保始终使用别名限定列:

SELECT 
    s.sno AS student_number
    , s.sname AS student_name
    , c.cname AS course_name
    , AVG(sc.grade) AS avg_grade
FROM
    sc
INNER JOIN 
    course c ON c.cno = sc.cno
INNER JOIN 
    stu s ON s.sno = sc.sno
GROUP BY
    s.sno
    , s.sname
    , c.cname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM