我有一个问题是在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
我需要从第一个选择返回按标题分组的所选书籍的数量,并在外部选择中选择最大数字,但也显示相应的书名。写得像这样,语句返回最大数字和按b.title分组的标题,这些数值不相关......
语句的以下部分仅返回最大数字,但我无法将其转换为返回标题:(:
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
请你帮我为我的目的创建真正的查询。
答案 0 :(得分:1)
您可以在主要选项中以“mn.title”的形式访问“b.title”。
我可以检查你的SQL句子的有效性,因为我不知道你的数据库结构。如果先前的建议不起作用,您可以发布您的数据库结构,以便我可以检查它并为您提供确切的SQL句子。
答案 1 :(得分:0)
您甚至不需要子查询:
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
如果有多个结果具有相同的最大计数,则需要子查询:
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