如何使用此查询获取10行和10分钟的行?

时间:2017-01-10 20:05:17

标签: php mysql

我使用以下查询来查找我的网页pageviews与过去2天相比的差异

SELECT PAGE, COUNT( * ) AS poso,
       (SUM(DATE(TIMESTAMP) = CURDATE()) - 
        SUM(DATE(TIMESTAMP) = DATE_SUB(CURDATE( ), INTERVAL 1 
DAY))
       ) diff
FROM  `behaviour` 
WHERE DATE( TIMESTAMP ) >= DATE_SUB( CURDATE( ) , INTERVAL 1 
DAY ) 
GROUP BY PAGE;

查询将页面返回给我。但是,我想要的是只有10行具有最大的正差异,而10则具有最大的负差异。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

使用两个查询的联合,一个获得前十名,另一个获得底部10 。查询将如下所示:

更新回答

SELECT 
    PAGE
    , poso
    , diff
from
    (
        (
            SELECT PAGE, COUNT( * ) AS poso,
                (SUM(DATE(TIMESTAMP) = CURDATE()) - 
                    SUM(DATE(TIMESTAMP) = DATE_SUB(CURDATE( ), INTERVAL 1 DAY))
                ) diff
            FROM  `behaviour` 
            WHERE 
                DATE( TIMESTAMP ) >= DATE_SUB( CURDATE( ) , INTERVAL 1 DAY ) 
            GROUP BY PAGE
            ORDER BY (SUM(DATE(TIMESTAMP) = CURDATE()) - 
                        SUM(DATE(TIMESTAMP) = DATE_SUB(CURDATE( ), INTERVAL 1 DAY))
                    ) desc
            LIMIT 10
        ) 
        UNION
        (   
            SELECT PAGE, COUNT( * ) AS poso,
                (SUM(DATE(TIMESTAMP) = CURDATE()) - 
                    SUM(DATE(TIMESTAMP) = DATE_SUB(CURDATE( ), INTERVAL 1 DAY))
                ) diff
            FROM  `behaviour` 
            WHERE 
                DATE( TIMESTAMP ) >= DATE_SUB( CURDATE( ) , INTERVAL 1 DAY ) 
            GROUP BY PAGE
            ORDER BY (SUM(DATE(TIMESTAMP) = CURDATE()) - 
                        SUM(DATE(TIMESTAMP) = DATE_SUB(CURDATE( ), INTERVAL 1 DAY))
                    ) asc
            LIMIT 10
        ) 
    ) as u
order by diff;