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的更好選擇。
這最後一個選項與最大值的行(S)將返回:
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
)
)
什麼是努力實現? – 2015-03-19 01:45:10
我試圖讓'max(count(DISTINCT order_id))'返回一個數字而不是一個錯誤。 – Blobert 2015-03-19 02:09:36
完成此操作的典型方法是按降序對計數表達式進行排序,然後將結果限制爲一行。如果你需要關係,那麼你可能不得不採取其他方法之一。 – shawnt00 2015-03-19 03:10:07