简体   繁体   English

如何计算mysql查询中的行?

[英]How to count rows in mysql query?

I want to query mysql according to row number ? 我想根据行号查询mysql吗? suppose I want to query last 10 rows , how to do this in mysql query? 假设我要查询最后10行,如何在mysql查询中执行此操作?

Here is my mysql query, but it queries according to 6 days interval, But I need to query it according to last 10 rows instead of 6 days interval, 这是我的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`

Make your query this: 进行以下查询:

SELECT * FROM people_history ORDER BY id DESC LIMIT 10

Limit allows you to limit the amount of results you get from a query. 限制允许您限制从查询中获得的结果数量。 By sorting by ID you can get the last 20 results in your table. 通过按ID排序,您可以获得表中的最后20个结果。

LIMIT : 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

And you might want to rewrite that query a little. 您可能想稍微重写一下该查询。

反转您的ORDER,因此后10个是前10个,LIMIT减10。

LIMIT will restrict the number of results returned. LIMIT将限制返回的结果数。 It goes at the end of the query. 它在查询的末尾。 Take a look at the documentation for SELECT , and go down to the LIMIT section. 查看SELECT文档 ,然后转到LIMIT部分。

For your query, if you add LIMIT 10 at the end, you will get only the 10 results you are looking for. 对于您的查询,如果在末尾添加LIMIT 10 ,则只会得到您要查找的10个结果。 Combine LIMIT with ORDER BY (ASC or DESC) to get the first or last results. 将LIMIT与ORDER BY(ASC或DESC)结合使用可获得第一个或最后一个结果。

well "last" has to refer to some sort of ordering (order by .... ) statement. 那么“最后”必须指某种排序(order by ....)语句。 you always add limit N (N=10 in your case) 您总是添加限制N(在您的情况下为N = 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM