2

我正在尝试创建一个查询,该查询返回另一个表中最多次数的事物的名称和国家/地区。

这是结构:

ShipModels(mname, type, country, numGuns, gunSize)
Ships(sname, hasModel, launchYear)
Battles(bname, year)
Outcomes(ship, battle, result)

我尝试了很多不同的东西,但无法让它发挥作用。这是我当前的查询:

SELECT ship, country
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
GROUP BY ship
HAVING COUNT(ship) >= 
( SELECT COUNT (ship) FROM Outcomes GROUP BY ship);

甲骨文错误:

ERROR at line 1:
ORA-00979: not a GROUP BY expression

根据我的阅读,当 SELECT 语句中有聚合函数时会引发此错误,但是......嗯,没有。有什么我想念的吗?我怎样才能让它工作?

4

2 回答 2

2

你包括countrySELECT

SELECT ship, country

但不在GROUP BY. 将该行更改为:

GROUP BY ship, country

当你更正它时,你会遇到另一个错误,因为子查询不是标量,例如不返回单个值:

( SELECT COUNT (ship) FROM Outcomes GROUP BY ship)

你可能打算写:

( SELECT MAX(cnt)
  FROM
    ( SELECT COUNT(ship) AS cnt FROM Outcomes GROUP BY ship ) t
)

因此,完整的查询将或多或少:

SELECT ship, country
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
GROUP BY ship, country
HAVING COUNT(ship) = 
    ( SELECT MAX(cnt)
      FROM
        ( SELECT COUNT(ship) AS cnt FROM Outcomes GROUP BY ship ) t
    ) ;

您也可以使用关键字将其编写得更像您的尝试ALL

SELECT ship, country
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
GROUP BY ship, country
HAVING COUNT(ship) >= ALL
    ( SELECT COUNT(ship) AS cnt FROM Outcomes GROUP BY ship ) ; 

如果您使用显式连接的“现代”(SQL-92) 语法也会很好。代替:

FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname

出于各种原因,最好写:

FROM ShipModels m
  JOIN Ships s ON s.hasModel = m.mname
  JOIN Outcomes o ON o.ship = s.sname  
于 2012-12-03T01:34:21.287 回答
0

问题在于 HAVING 子句中的 count(ship)。我认为这是 select 语句中的聚合函数。

于 2012-12-03T00:17:43.153 回答