MySQL代码错误-内部联接时的语法错误

时间:2019-06-14 18:40:15

标签: mysql

我有2个表-部门和员工。我正在尝试显示至少雇用1名员工的部门,这些部门必须按部门ID

进行排序

部门表

create table department (
      dept_id integer not null,
      dept_name varchar(30) not null,
      dept_location varchar(30) not null,
      unique(dept_id)
  );

员工表


  create table employee (
      emp_id integer not null,
      emp_name varchar(50) not null,
      dept_id integer not null,
      salary integer not null,
      unique(emp_id)
  );

我已经编写了此SQL查询

SELECT  department.dept_id, sum(salary),count(*) 
FROM employee 
     INNER JOIN department
       ON employee.dept_id =department.dept_id
        GROUP BY department.dept_id
          HAVING COUNT(*) > 0;
ORDER BY department.dept_id

我得到

syntax error at or near "ORDER"

1 个答案:

答案 0 :(得分:1)

您的order by子句位置错误。

顺序必须是最后一个子句

SELECT  department.dept_id, sum(employee.salary), count(*) 
FROM employee 
     INNER JOIN department
       ON employee.dept_id =department.dept_id
        GROUP BY department.dept_id
          HAVING COUNT(*) > 0
ORDER BY department.dept_id; 

这是因为ORDER BY只能用于结果显示