简体   繁体   中英

Ambiguous error when using INNER JOIN

I am trying to select deptno, dname from the depts table and join it with the emp table to select empno and ename. Then I want group them by department name by sort by deptno ascending.
When joining these two tables I keep getting 'deptno' is ambiguous. But that is the commonality to join the tables. Any helpful advice where my error may be with

SELECT deptno, dname, empno, ename
FROM dept INNER JOIN emp
ON dept.deptno = emp.deptno
GROUP BY dname
ORDER BY deptno ASC; 

Thank you for any helpful advice.

Ambiguity arises from the deptno field, which is present in both the dept and emp tables. To avoid it use qualified names or aliases.

SELECT D.deptno, dname, empno, ename
FROM dept D
    INNER JOIN emp E
        ON D.deptno = E.deptno
GROUP BY dname
ORDER BY D.deptno ASC; 
SELECT dept.deptno, dname, empno, ename FROM dept INNER JOIN emp ON dept.deptno = emp.deptno   
GROUP BY dname ORDER BY dept.deptno ASC;

The problem is that you have deptno in both tables but you are not specifying which table to return in both the SELECT and ORDER BY :

SELECT dept.deptno, dname, empno, ename
FROM dept 
INNER JOIN emp
  ON dept.deptno = emp.deptno
GROUP BY dname
ORDER BY dept.deptno ASC; 

Or

SELECT emp.deptno, dname, empno, ename
FROM dept 
INNER JOIN emp
  ON dept.deptno = emp.deptno
GROUP BY dname
ORDER BY emp.deptno ASC; 

If you do not specify the table for deptno , then you will get this error message.

try this

 SELECT dept.deptno, dname, empno, ename
 FROM dept INNER JOIN emp
 ON dept.deptno = emp.deptno
 GROUP BY dname
 ORDER BY dept.deptno ASC; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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