GROUP BY具有最新元素

时间:2012-10-03 15:30:23

标签: mysql sql

通常我们使用SELECT MAX(datetime)和GROUP BY(page_ID)来获取最新页面,但我不明白为什么它在这里不起作用。

我的以下查询应该只选择行ID 75和77,但是它选择75和76: enter image description here

SELECT ru.page_ID AS id, 
    pFrom.name AS name,
    UNIX_TIMESTAMP(ru.rating_time) AS action_date,                          
    ru.current_rank AS current_rank,        
    MAX(ru.rating_time)                     
FROM ranks_update ru
INNER JOIN pages pFrom
    ON ru.page_ID = pFrom.page_ID
WHERE ru.ranking_ID = :id_rk
    AND ru.page_ID IN ( ** subquery 1 **)
    AND ru.rating_time >= ( ** subquery  2 **)                      
GROUP BY ru.page_ID                             
ORDER BY ru.current_sum_vote DESC

2 个答案:

答案 0 :(得分:2)

select ru.page_ID AS id, 
    pFrom.name AS name,
    UNIX_TIMESTAMP(ru.rating_time) AS action_date,                          
    ru.current_rank AS current_rank,        
    rum.MaxDate
from ranks_update ru
inner join(
    select page_ID, MAX(rating_time) as MaxDate
    from ranks_update
    WHERE ranking_ID = :id_rk
        AND page_ID IN ( ** subquery 1 **)
        AND rating_time >= ( ** subquery  2 **)   
    group by page_ID
) rum on ru.page_ID = rum.page_ID and ru.rating_time = rum.MaxDate
inner join pages pFrom on ru.page_ID = pFrom.page_ID
ORDER BY ru.current_sum_vote DESC

答案 1 :(得分:0)

一个促成因素将是MySQL对GROUP BY的古怪解释。在标准SQL中,您必须指定所有非聚合列(例如:GROUP BY ru.page_ID, pFrom.name, ru.currentRank, ru.current_sum_vote)。 MySQL将允许你不这样做,但它的行为是未定义的,很可能是随机的。如果您编写标准SQL,您将获得可预测的结果。