Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

This is strictly a perl question, but it will be used in my perl script.. What I am wanting to do is query the sql database and get the 5 latest articles .. they are all incremented by ID so I could get the 5 largest id numbers...but I have no idea what the actual sql quer would be to do this :(

Any ideas? Thanks you very much

Replies are listed 'Best First'.
(shockme) Re: MySQL Query
by shockme (Chaplain) on Nov 22, 2001 at 06:22 UTC
    You don't really provide enough information to allow for a complete answer. However, given that you have an ID, you probably want to check out the DESC keyword. Something like:

    SELECT whatever FROM table ORDER BY id DESC;

    The results will be sorted in descending (or reverse) order. See http://www.mysql.com/doc/S/o/Sorting_rows.html for more information.

    If things get any worse, I'll have to ask you to stop helping me.

      ... and adding
      LIMIT 5
      to the end will with some database servers just give you the first five records of the result set.

       - ask

      -- 
      ask bjoern hansen, http://ask.netcetera.dk/   !try; do();
      
Re: MySQL Query
by guha (Priest) on Nov 22, 2001 at 13:29 UTC
    LIMIT works for MySQL, below an excerpt from the Man

    The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
    LIMIT takes one or two numeric arguments.
    If two arguments are given, the first specifies the offset of the first row to return, the second specifies the maximum number of rows to return.
    The offset of the initial row is 0 (not 1):

    mysql> select * from table LIMIT 5,10; # Retrieve rows 6-15

    If one argument is given, it indicates the maximum number of rows to return:

    mysql> select * from table LIMIT 5; # Retrieve first 5 rows

    In other words, LIMIT n is equivalent to LIMIT 0,n.

    HTH

Re: MySQL Query
by Elgon (Curate) on Nov 22, 2001 at 18:56 UTC

    Anonymous monk,

    I was doing this very thing yesterday for my final year project for my chemistry degree(A web-enabled chemical database of compounds which does all sorts of pretty things - alas in PHP not Perl but you can't have everything.)

    select STUFF from TABLE order by INDEX/DATE desc limit 5;

    Just replace STUFF with the column names you want, TABLE with the table name and INDEX/DATE with whatever you want to index it by (the desc tells it to do it in reverse order, sorting so that older dates end up last and newer ones first.)

    "A nerd is someone who knows the difference between a compiled and an interpreted language, whereas a geek is a person who can explain it cogently over a couple of beers" - Elgon