column reference "group_id" is ambiguous when join

huangapple go评论89阅读模式
英文:

column reference "group_id" is ambiguous when join

问题

我在连接两个表时遇到了一些问题:

Groups(分组):group_id(分组ID),group_name(分组名称)

Students(学生):student_id(学生ID),group_id(分组ID),first_name(名),last_name(姓)

我想要计算每个分组有多少名学生,然后输出分组名称。但是当我写成这样时:

public String findGroupsByStudentsNumber(int expectedStudentsNumber) {
        return "SELECT group_id, COUNT(student_id) AS Number_of_students " +
                "FROM students " +
                "LEFT JOIN groups ON group_id = groups.group_id " +
                "GROUP BY group_id " +
                "HAVING Number_of_students <= " + expectedStudentsNumber +
                " ORDER BY group_id";
    }

出现了错误提示:“列引用"group_id"不明确”。

英文:

I have some troubles with join two tables:

Groups: group_id, group_name

Students: student_id, group_id, first_name, last_name

I wanna count how many students have each group and then output group name, but when i write like this:

public String findGroupsByStudentsNumber(int expectedStudentsNumber) {
        return &quot; SELECT group_id, COUNT(student_id) AS Number_of_students &quot; +
                &quot;FROM students &quot; +
                &quot;LEFT JOIN groups ON group_id = groups.group_id &quot; +
                &quot;GROUP BY group_id &quot; +
                &quot;HAVING Number_of_students &lt;=&quot; + expectedStudentsNumber +
                &quot; ORDER BY group_id&quot;;
    }

there is an error "column reference "group_id" is ambiguous".

答案1

得分: 1

因为两个表格都有一个 group_id 列,所以在查询中不能使用简单的 group_id,而不指定你要引用哪个表格的列。以下是可能的一种写法:

SELECT students.group_id, COUNT(student_id) AS 学生人数
FROM students
LEFT JOIN groups ON students.group_id = groups.group_id
GROUP BY students.group_id 
HAVING 学生人数 <= X
ORDER BY students.group_id
英文:

Since both tables have a group_id column, you can't have a plain group_id in your query without specifying which one you're referring to. This is one way it could look:

SELECT students.group_id, COUNT(student_id) AS Number_of_students
FROM students
LEFT JOIN groups ON students.group_id = groups.group_id
GROUP BY students.group_id 
HAVING Number_of_students &lt;= X
ORDER BY students.group_id

huangapple
  • 本文由 发表于 2020年8月15日 15:05:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63423492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定