简体   繁体   English

在其他select语句中选择最大值,并从嵌套的select中显示一个相关字段

[英]Select max value within other select statement and display also a relevant field from the nested select

I have a problem to express the next statement on mySql to return true results: 我有一个问题要在mySql上表达下一条语句以返回真实结果:

     select max(alltaken)mn, b.title from 
     (select  count(bc.taken) as alltaken, b.title
     from books_clients bc
     join books b on b.book_id = bc.book_id
     group by b.title) as mn
     join books b on b.title = mn.title

I need to return from the first select the count of the taken books grouped by title and in the external select to select the max number but also to display the corresponding title of the book. 我需要从第一个选择返回的书名按标题归类,然后在外部选择中返回以选择最大数量,还要显示相应的书名。 Written like this the statement returns the max number and the title grouped by b.title, values which are not related... 这样写的语句将返回最大数目和按b.title分组的标题,不相关的值...

The following part of the statement returns only the max number, but I cannot transform it to return the title too :( : 语句的以下部分仅返回最大数,但我也无法将其转换为也返回标题:(:

    select max(alltaken)mn
    (select  count(bc.taken) as alltaken, b.title
    from books_clients bc
    join books b on b.book_id = bc.book_id
    group by b.title) as mn 

Could you please help me to create the true query for my purpose. 您能否帮助我为我创建真正的查询。

You can access to "b.title" in your main select as "mn.title". 您可以在主要选择的“ mn.title”中访问“ b.title”。

I can check the validity of your SQL sentence because I don't know your database structure. 我不知道您的数据库结构,因此可以检查您的SQL语句的有效性。 If previous suggestion doesn't works you can publish your database structure so I can check it and give you the exact SQL sentence. 如果先前的建议不起作用,则可以发布数据库结构,以便我检查它并提供确切的SQL语句。

You don't even need a subquery: 您甚至不需要子查询:

SELECT COUNT(bc.taken) AS mn
     , b.title
FROM books_clients AS bc
  JOIN books b 
    ON b.book_id = bc.book_id
GROUP BY b.title
ORDER BY mn DESC
LIMIT 1

If there are more than one results with same Max count, then you need a subquery: 如果有多个具有相同最大计数的结果,则需要一个子查询:

SELECT allb.mn
     , allb.title
FROM 
    ( SELECT COUNT(bc.taken) AS mn
      FROM books_clients AS bc
        JOIN books b 
          ON b.book_id = bc.book_id
      GROUP BY b.title
      ORDER BY mn DESC
      LIMIT 1
    ) AS maxb
  JOIN
    ( SELECT COUNT(bc.taken) AS mn
           , b.title
      FROM books_clients AS bc
        JOIN books b 
          ON b.book_id = bc.book_id
      GROUP BY b.title
    ) AS allb
    ON allb.mn = maxb.man

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM