如何计算mysql查询中的行数?

时间:2012-05-02 15:06:56

标签: php mysql phpmyadmin

我想根据行号查询mysql?假设我想查询最后10行,如何在mysql查询中执行此操作?

这是我的mysql查询,但它按照6天的间隔进行查询,但是我需要根据最后10行而不是6天的间隔查询它,

SELECT people_id, people_number 'people number', count(people_number) 'Occurs',
  (
   Select count(people_number) from people_history
   where people_id =  5486 and date > DATE_SUB(NOW(), INTERVAL 6 DAY)
  ) 'Total',
  count(people_number)/(
      Select count(people_number) from people_history
      where people_id = 5486 and date > DATE_SUB(NOW(), INTERVAL 6 DAY)
  )*100 'Percent'
FROM people_history
where people_id = 5486 and date > DATE_SUB(NOW(), INTERVAL 6 DAY)
group by people_id, people_number
order by Percent desc`

5 个答案:

答案 0 :(得分:4)

进行查询:

SELECT * FROM people_history ORDER BY id DESC LIMIT 10

Limit允许您限制从查询中获得的结果数量。通过按ID排序,您可以在表格中获得最后20个结果。

答案 1 :(得分:1)

LIMIT

SELECT 
    people_id,
    people_number 'people number',
    count(people_number) 'Occurs',
    (Select 
        count(people_number) 
    from 
        people_history 
    where 
        people_id = 5486 
        and date > DATE_SUB(NOW(), INTERVAL 6 DAY)) 'Total',            
    count(people_number) / 
        (Select 
            count(people_number) 
        from 
            people_history 
        where 
            people_id = 5486 
            and date > DATE_SUB(NOW(), INTERVAL 6 DAY)) *100 'Percent' 
FROM 
    people_history 
WHERE
    people_id = 5486 
    and date > DATE_SUB(NOW(), INTERVAL 6 DAY)
GROUP BY
    people_id, people_number 
ORDER BY 
    Percent desc
LIMIT 0, 10

你可能想稍微重写那个查询。

答案 2 :(得分:1)

反转你的ORDER,所以最后10个是前10个,LIMIT是10个。

答案 3 :(得分:1)

LIMIT会限制返回的结果数量。它在查询结束时发生。看看documentation for SELECT,然后转到LIMIT部分。

对于您的查询,如果您在结尾添加LIMIT 10,则只会获得您要查找的10个结果。将LIMIT与ORDER BY(ASC或DESC)组合以获得第一个或最后一个结果。

答案 4 :(得分:0)

好“最后”必须引用某种排序(order by ....)语句。你总是加上限制N(在你的情况下N = 10)