【问题标题】:how to get count from two tables without subquery in mysql如何从mysql中没有子查询的两个表中获取计数
【发布时间】:2012-01-26 05:28:28
【问题描述】:

我有两张桌子,

department  
———-  
deptid (type: INT)  
deptname (type: TEXT)  
hours (type: INT)  
active (type: BIT)  

employee  
——–  
empid (type: INT)  
empname (type: TEXT)  
deptid (type: INT)  
designation (type: TEXT)  
salary (type: INT)  

现在如何在不使用返回列 empname 和 deptname 的子查询的情况下进行查询,该列属于员工人数为 4 或更多的部门的员工。记录应按 empname 的字母顺序返回。

【问题讨论】:

  • 我做了这样的解决方案:select e.empname , d.deptname, d.deptidfrom employee e inner join department d where e.deptid = d.deptid and e .deptid in (select deptid from employee group by deptid have (count(deptid)) >= 4) order by e.empname;但我想要它没有子查询。

标签: php mysql


【解决方案1】:

因为您有一个聚合条件(人数为 4 或更多),这意味着没有子查询您无法获得empname,而只能获得deptname

【讨论】:

    【解决方案2】:
    Select E.empName, D.DeptName, count(E2.EmpID)
    FROM Department D
    LEFT JOIN Employee E
      ON E.DeptID = D.DeptID
    LEFT JOIN Employee E2
      ON E.DeptID = D.DeptID
    GROUP BY E.EmpName, D.DeptName
    Having count(e2.empID) >=4
    

    【讨论】:

      【解决方案3】:

      我还没有测试过,但这对我来说是正确的

      SELECT empname, deptname, department.deptid
      FROM employee JOIN department ON employee.deptid = department.deptid
      GROUP BY department.deptid
      HAVING count(department.deptid) >= 4
      ORDER BY empname;
      

      【讨论】:

      • 如果您按部门 id 对它们进行分组,那么您将看不到每个部门的所有名称。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多