如何取消MySQL中having子句的组效应?

How to undo the group effect of having clause in MySQL?

查询:对于每位获得超过三架飞机认证的飞行员,找出每架飞机的eid和最大续航里程he/she 已通过认证。

我写的查询:

select certified.eid,cruising_range
from certified join employee 
on employee.eid=certified.eid
join aircraft
on certified.aid=aircraft.aid
having count(certified.eid)>3;

输出:

它只显示一个续航里程,但是 id 10 的飞行员获得了 4 架飞机 的认证。如何获取其他行?

使用 group by certified.eid .

The count is an aggregate operator, which makes only one row returned (without a group by clause)

select certified.eid,cruising_range
from certified join employee 
on employee.eid=certified.eid
join aircraft
on certified.aid=aircraft.aid
group by certified.eid`
having count(certified.eid)>3;

没有按聚合函数分组return只有一行

您的问题实际上分为两个部分:

  1. 查找获得三架以上飞机认证的飞行员

    SELECT eid FROM certified GROUP BY eid HAVING COUNT(*) > 3
    
  2. 求出那些飞机的续航里程

    SELECT eid, cruising_range FROM aircraft JOIN certified USING (aid) ...
    

结合两者:

SELECT eid, cruising_range FROM aircraft JOIN certified USING (aid) JOIN (
  SELECT eid FROM certified GROUP BY eid HAVING COUNT(*) > 3
) t USING (eid)