如何通过MySQL中结果总数的百分比来限制查询结果?

时间:2017-02-03 21:51:03

标签: mysql sql sql-limit

下面的mysql问题只返回10个第一行。我怎样才能将它们限制在全部的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) AS u 
ORDER  BY diff DESC 

1 个答案:

答案 0 :(得分:0)

改编自the answer to the duplicate question

SELECT page,
       poso,
       diff
FROM    (
    SELECT *,
           @counter := @counter + 1 AS counter
    FROM   (select @counter:=0) AS initvar, 
           (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) AS u
) AS v
WHERE counter <= 10/100 * @counter
ORDER  BY diff DESC;

在这里演示:http://rextester.com/JKMBZR62923