last entry in a column

Discussion in 'MySQL' started by Philosophaie, Feb 16, 2012.

  1. #1
    Is there a way of getting the last entry in a column?

    $conn = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
    mysql_select_db('database1');
    $sql = "SELECT field4 From table1 WHERE field4=???";
    $lastentry_field4 = mysql_query($sql, $conn) or die('Query failed: ' . mysql_error());
    Code (markup):
     
    Philosophaie, Feb 16, 2012 IP
  2. alanchavezv

    alanchavezv Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This should get the job done

    SELECT field4 from table1 WHERE field4=??? ORDER BY field4 DESC LIMIT 0,1
    Code (markup):
     
    alanchavezv, Feb 17, 2012 IP
  3. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #3
    If you mean the last one inserted, not unless you also save the insertion date/time. There's no guarantee of order in a database. The first record returned could be the first one inserted or the last one inserted.

    Ordering by the field (if the field isn't the insertion date/time) will only work if that field's data is constantly increasing record to record.
     
    Rukbat, Feb 25, 2012 IP
  4. GodOfTerror

    GodOfTerror Peon

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The last ENTRY in a column is best found if it has an ID
    or a TIME STAMP.

    if there is neither ID or TIMESTAMP then it can not be found.

    if it has an ID or a TIMESTAMP then you can do the mysql's "desc"

    to get the last item.

    for example " SORT BY _ID_, desc "

    - Sumer Kolcak
     
    GodOfTerror, Mar 11, 2012 IP