检索包含字段最大值的整个行

时间:2013-01-25 17:52:28

标签: mysql sql greatest-n-per-group

我想计算出租借的书籍数量最多的主题区域。我有以下查询:

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

但是,整个查询将结果显示为Biology(而不是DBMS)。请说明为什么会发生这种情况

2 个答案:

答案 0 :(得分: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

祝你好运。

答案 1 :(得分: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))。
  • 然后只选择总和与最大值(HAVING)匹配的结果。

P.S。:正如其他人所建议的那样,使用显式列名(代替NATURAL JOIN)将使您的代码更少"脆弱"。

P.P.S。:您应该为这些问题提供数据库结构,甚至更好地提供一个有效的sqlfiddle.com示例,以便我们立即测试答案。