Skip to main content
Known Participant
May 18, 2008
Answered

Last n records

  • May 18, 2008
  • 2 replies
  • 485 views
Yes – I’m working on a Sunday.

Okay, here’s the deal: I want to retrieve the last n (call it 5) records (non-sequential) from a table. I can easily do this by getting my query to sort desc, and then using maxrows so that it gives me the last 5 – but:

1) I want the last 5 to be in order – for example, I don’t want 10, 9, 8, 7, 6, - which is what the example above gives me, I want 6, 7, 8, 9, 10.
2) The table will have thousands, if not 10s of thousands of records, to select just the row_id desc, will be a huge task. Don’t want the server to work that hard – it’s got other things to do.

My idea is as follows – using the select max(row_id) is easy, it gives me the last record – can't I just do something that will step back n number times from my max query and give me the last n records?

PS: MX8, MySql 5
    This topic has been closed for replies.
    Correct answer johnab
    ideally you need to be letting the database do the work here, not ColdFusion - with mysql you want to be looking at the 'limit' sql directive as it will do everything you want.

    2 replies

    johnabCorrect answer
    Participating Frequently
    May 18, 2008
    ideally you need to be letting the database do the work here, not ColdFusion - with mysql you want to be looking at the 'limit' sql directive as it will do everything you want.
    JellyheadAuthor
    Known Participant
    May 18, 2008
    Sweet, works a treat!

    I did the following:


    <cfquery name="getmax" datasource="#dsn#">
    select max(rowid) as maxx from table
    </cfquery>

    <cfset startlimit=#getmax.maxx#-3>

    <cfquery name="getrecent" datasource="#dsn#">
    select rowid from table LIMIT #startlimit#, 3
    </cfquery>

    I've just learned something! Thank you
    Inspiring
    May 18, 2008
    add another query before your query:
    <cfquery name='getrowcount' ...>
    SELECT COUNT(*) AS ttlrows
    FROM yuortable
    </cfquery>

    in your current query add the following as last line:

    LIMIT #getrowcount.ttlrows-5#, 5



    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com/