仅返回MySQL中列的最高值

时间:2015-03-19 00:37:08

标签: mysql

任何人都可以解释如何解决这个问题吗?

SELECT book_id, title, count(DISTINCT order_id)
FROM a_bkinfo.books
JOIN a_bkinfo.book_topics USING (book_id)
JOIN a_bkorders.order_details USING (book_id)
WHERE topic_id IN ("FCT", "POE")
GROUP BY book_id;


1077    Programming for Poets   2
1103    Selected Poems  34
1133    Leaves of Grass 4
1304    Stories of Discoveries  6
1306    Myths of SQL    3
1602    Goblin Market and Other Poems   4

我只想要返回右边最高值的行(即#34;选择诗歌")。我将如何完成这项工作?

1 个答案:

答案 0 :(得分:0)

select max(order_count) from (
    SELECT count(DISTINCT order_id) as order_count
    FROM a_bkinfo.books
    JOIN a_bkinfo.book_topics USING (book_id)
    JOIN a_bkorders.order_details USING (book_id)
    WHERE topic_id IN ("FCT", "POE")
    GROUP BY book_id
) T

这是一个标量结果,所以你应该能够将它添加到选择列表上的原始查询中,如果你想看到它附加到每一行:

select ..., (
    select max(order_count) from (
        SELECT count(DISTINCT order_id) as order_count
        FROM a_bkinfo.books
        JOIN a_bkinfo.book_topics USING (book_id)
        JOIN a_bkorders.order_details USING (book_id)
        WHERE topic_id IN ("FCT", "POE")
        GROUP BY book_id
    ) as max_order_count
from ...

或者您可以使用交叉连接

select ...
from ...
    JOIN a_bkorders.order_details USING (book_id),
    (
        select max(order_count) from (
            SELECT count(DISTINCT order_id) as order_count
            FROM a_bkinfo.books
            JOIN a_bkinfo.book_topics USING (book_id)
            JOIN a_bkorders.order_details USING (book_id)
            WHERE topic_id IN ("FCT", "POE")
            GROUP BY book_id
        ) T
    ) T2
where ...

不确定哪个是MySQL更好的选择。

最后一个选项将返回具有最大值的行:

SELECT book_id, title, count(DISTINCT order_id)
FROM a_bkinfo.books
JOIN a_bkinfo.book_topics USING (book_id)
JOIN a_bkorders.order_details USING (book_id)
WHERE topic_id IN ("FCT", "POE")
GROUP BY book_id
HAVING count(DISTINCT order_id) = (
    select max(order_count) from (
        SELECT count(DISTINCT order_id) as order_count
        FROM a_bkinfo.books
        JOIN a_bkinfo.book_topics USING (book_id)
        JOIN a_bkorders.order_details USING (book_id)
        WHERE topic_id IN ("FCT", "POE")
        GROUP BY book_id
    )
)