Results 1 to 5 of 5

Thread: group by help?

  1. #1
    Join Date
    Jan 2004
    Posts
    35

    Question Unanswered: group by help?

    I am trying to get the last occurance of a display name in a login user log database. Basically I have a table that looks like this:

    id user fname lname
    -----------------------------------
    1 jdoe Jane Doe
    2 jdoe John Doe
    3 jdoe Fred Flinstone


    I run the MySQL query: SELECT name, max(id) as max_id, user FROM `logins` GROUP BY user

    I get back:
    id user fname lname
    -----------------------------------
    3 jdoe Jane Doe


    I actually want:
    id user fname lname
    -----------------------------------
    3 jdoe Fred Flinstone


    Any that can help it would be greatly Appreciated!!

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    by "last" occurrence you mean the one with the largest id?
    Code:
    select id
         , user
         , fname
         , lname 
      from logins as ZZ
     where id 
         = ( select max(id)
               from logins
              where user = ZZ.user )
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Jan 2004
    Posts
    35
    I tried this result and am still having difficulties? Do you know if this works with all versions of MySQL? I get the following error from phpmyadmin:

    You have an error in your SQL syntax near 'select max(id) from logins where user=ZZ.user

    Any other thoughts?

  4. #4
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    good guess -- subqueries are not supported prior to version 4.1

    how come it took you two and a half weeks to try my solution?
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  5. #5
    Join Date
    Sep 2004
    Location
    Belgium
    Posts
    1,126
    If a correlated subquery is not supported, let's hope a join (and a group by) is?
    Could you try this one:
    Code:
      select a.id, a.user, a.fname, a.lname
        from logins as a, logins as b
       where a.user = b.user
         and a.id <= b.id
    group by a.id, a.user, a.fname, a.lname
      having count(*) = 1
    --_Peter Vanroose,
    __IBM Certified Database Administrator, DB2 9 for z/OS
    __IBM Certified Application Developer
    __ABIS Training and Consulting
    __http://www.abis.be/

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •