2

我想计算出借书数量最多的学科领域。我有以下查询:

SELECT SubjectArea
FROM (

  SELECT SubjectArea, MAX( Copies_On_Loan ) AS Max
  FROM (

    SELECT
      Section.SubjectArea AS SubjectArea, 
      SUM( LoanBook.Copies_On_Loan ) AS Copies_On_Loan
    FROM Section
      NATURAL JOIN Items
      NATURAL JOIN LoanBook
    GROUP BY Section.SubjectArea
  ) AS Table1
) AS Table2

最里面的查询:

    SELECT 
      Section.SubjectArea AS SubjectArea, 
      SUM( LoanBook.Copies_On_Loan ) AS Copies_On_Loan
    FROM Section
      NATURAL JOIN Items
      NATURAL JOIN LoanBook
    GROUP BY Section.SubjectArea

返回下表:

SubjectArea Copies_On_Loan
Biology         0
DBMS            3

但是,整个查询给出的结果是生物学(而不是 DBMS)。请提出为什么会这样

4

2 回答 2

0

在我的脑海中,看起来你需要类似的东西:

SELECT SubjectArea
FROM Section NATURAL JOIN Items NATURAL JOIN LoanBook
GROUP BY SubjectArea
HAVING SUM(Copies_On_Loan) = (
    SELECT MAX(M) (
        SELECT SUM(Copies_On_Loan) M
        FROM Section NATURAL JOIN Items NATURAL JOIN LoanBook
        GROUP BY SubjectArea
    ) Q1
) Q2

计划中的英语:

  • 对每个主题的贷款求和 ( SUM(Copies_On_Loan) M) 并找到最大总和 ( MAX(M))。
  • 然后只选择 sum 与最大值 ( ) 匹配的那些结果HAVING

PS:正如其他人所建议的那样,使用显式列名(代替 NATURAL JOIN)将使您的代码不那么“脆弱”。

PPS:你真的应该为这些问题提供数据库结构,或者更好的是一个有效的 sqlfiddle.com 示例,这样我们就可以立即测试答案。

于 2013-01-25T18:49:12.517 回答
0

好的,我想我明白您想要什么——您正在尝试获取具有 Max(Copies_On_Loan) 的主题。如果是这样,这应该可以工作(如果 MySQL 支持 CTE 会更漂亮):

SELECT SubjectArea
FROM (
  SELECT MAX( Copies_On_Loan ) AS Max_Copies_On_Loan 
  FROM (
    SELECT
      Section.SubjectArea AS SubjectArea, 
      SUM( LoanBook.Copies_On_Loan ) AS Copies_On_Loan
    FROM Section
      NATURAL JOIN Items
      NATURAL JOIN LoanBook
    GROUP BY Section.SubjectArea
  ) AS Table1
) AS Table2 JOIN 
(
   SELECT
      Section.SubjectArea AS SubjectArea, 
      SUM( LoanBook.Copies_On_Loan ) AS Copies_On_Loan
    FROM Section
      NATURAL JOIN Items
      NATURAL JOIN LoanBook
    GROUP BY Section.SubjectArea
) Table3 ON Table2.Max_Copies_On_Loan  = Table3.Copies_On_Loan

这是更新的SQL Fiddle

祝你好运。

于 2013-01-25T18:02:58.160 回答