2012-05-02 83 views
0

我想根據行號查詢mysql嗎?假設我想查詢最後10行,如何在mysql查詢中做到這一點?如何計算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

讓您的查詢這樣的:

SELECT * FROM people_history ORDER BY id DESC LIMIT 10 

Limit可以限制的結果你從查詢得到的金額。通過按ID排序,您可以獲取表格中的最後20個結果。

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

小心地擴大一點? –

+0

10行什麼'LIMIT'我需要使用 – Jeniffer

0

well「last」必須引用某種排序(order by ....)語句。你總是由10

+0

SELECT people_id,people_number'people number',count(people_number)'Occurs',(Select people_history where people_id = 5486 and date> DATE_SUB(NOW() ,INTERVAL 6 DAY))'total',count(people_number)/(從people_history中選擇count(people_number),其中people_id = 5486且日期> DATE_SUB(NOW(),INTERVAL 6 DAY))* 100'Percent'FROM people_history where people_id = 5486和日期> DATE_SUB(NOW(),INTERVAL 6 DAY)group by people_id,people_number order by Percent desc limit 10 – tipanverella

1

反向您的訂單,所以最後10是第10位,該限制將制約的結果數返回。它在查詢的最後。看看documentation for SELECT,然後轉到LIMIT部分。

對於您的查詢,如果您在最後加上LIMIT 10,您將只能得到您要查找的10個結果。將LIMIT和ORDER BY(ASC或DESC)結合起來得到第一個或最後一個結果。

1

LIMIT加限制N(N你的情況= 10)