什么是我的SQL查询

时间:2018-05-22 11:00:16

标签: mysql sql mysqli

我的数据库中有2个表。

 Table 1. employee
id
name
department_id



 Table 2. department
id
name

现在我有两个问题。

1.用他们的部门获取所有员工的查询是什么? 所以我写了这个查询

SELECT employee.name
     , department.name 
  FROM employee 
  JOIN department 
    ON employee.department_id = department.id

这似乎是正确的,但我无法为下一个问题编写查询。

问题是:

如果我只想获取员工人数最多的部门?

5 个答案:

答案 0 :(得分:1)

只保证 一个 部门......

SELECT
  *
FROM
  department
WHERE
  id = (SELECT department_id
          FROM employee
      GROUP BY department_id
      ORDER BY COUNT(*) DESC
         LIMIT 1
       )

注意,如果两个部门与联合最大雇员捆绑在一起,那么仍然只选择其中一个(任意选择,每次可能不同)。

要处理关系,您可以执行以下操作...

SELECT *
  FROM department
 WHERE id IN (SELECT department_id
                FROM employee
            GROUP BY department_id
              HAVING COUNT(*) = (SELECT COUNT(*)
                                   FROM employee
                               GROUP BY department_id
                               ORDER BY COUNT(*) DESC
                                  LIMIT 1
                                )
             )

答案 1 :(得分:0)

在MySQL中处理这是一个真正的痛苦。这是一个选项:

SELECT d1.id, d1.name
FROM department d1
INNER JOIN employee e1
    ON d1.id = e1.department_id
GROUP BY d1.id, d1.name
HAVING COUNT(*) = (SELECT COUNT(*) FROM department d2 INNER JOIN employee e2
                       ON d2.id = e2.department_id
                   GROUP BY d2.id ORDER BY COUNT(*) DESC LIMIT 1);

请注意,如果您使用的是具有分析功能支持的数据库(如SQL Server),则问题会变得更加容易:

SELECT id, name
FROM
(
    SELECT d.id, d.name, DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) dr
    FROM department d
    INNER JOIN employee e
        ON d.id = e.department_id
    GROUP BY d.id, d.name
) t
WHERE t.dr = 1;

答案 2 :(得分:0)

这个问题可以通过多种方式解决:

使用子查询

SELECT name FROM department
WHERE id IN
(SELECT department_id FROM employee HAVING COUNT(department_id)
IN
(SELECT MAX(COUNT(department_id)) FROM employee) GROUP BY department_id)

使用加入

SELECT name FROM employee e
INNER JOIN
department d ON e.department_id = d.id
HAVING COUNT(e.department_id)
IN
(SELECT MAX(COUNT(department_id)) from employee) group by department_id)

答案 3 :(得分:0)

首先检查列相关的两个类型是否具有相同的名称,相同的数据类型和使用子查询, SELECT name FROM department WHERE id IN(SELECT department_id FROM employees HAVING COUNT(department_id)IN(SELECT MAX(COUNT(dept_id))FROM employees)GROUP BY department_id)

答案 4 :(得分:-2)

您的查询应该适用于第一个问题。

第二个,你可以使用它。子查询将为您提供最多员工的部门ID,外部查询将为其提供其他详细信息。

select * from department where department_id in
(select limit 1 Employee.department_id from Employee group by department_id 
order by count(Employee.name) desc)