0

我想根据行号查询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`
4

5 回答 5

4

使您的查询:

SELECT * FROM people_history ORDER BY id DESC LIMIT 10

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

于 2012-05-02T15:08:55.787 回答
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

您可能想要稍微重写该查询。

于 2012-05-02T15:08:25.627 回答
1

颠倒你的订单,所以最后 10 个是前 10 个,限制为 10。

于 2012-05-02T15:10:30.863 回答
1

LIMIT将限制返回结果的数量。它在查询的末尾。查看SELECT的文档,然后转到 LIMIT 部分。

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

于 2012-05-02T15:11:07.580 回答
0

好吧,“last”必须指某种排序(order by ....)语句。你总是添加限制 N (在你的情况下 N = 10)

于 2012-05-02T15:10:14.107 回答