SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2001
    Location
    Helston, Cornwall, England
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Another group by, order by query

    Hi all,

    I have a question regarding the use of group by and order by in the same query.

    I am trying to return a return a set of random results from a database, order by RAND(), but have them grouped together, by another field.

    SELECT * FROM "db" WHERE town LIKE '$town' ORDER BY RAND()

    Returns all the results in random order. I now want to group them with by another field.

    SELECT * FROM "db" WHERE town LIKE '$town' GROUP BY sleeps ORDER BY RAND()

    This works but obviously only returns 1 set of sleeps field, how do I return all entries?

    http://www.choosespain.com/newtownpage.php is a basic order by RAND(), but as you'll see I need to Group the random results by the number of persons each property sleeps.

    Hope I've explained myself ok.

    Thanks in advance

    Warren

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,350
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    when you say "have them grouped together, by another field" what you really mean is order them in random sequence within sleeps

    SELECT * FROM "db"
    WHERE town LIKE '$town'
    ORDER BY sleeps desc, RAND()

    also, note that without wildcards, you might as well use = instead of LIKE
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2001
    Location
    Helston, Cornwall, England
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Rudy, thanks for that and the explanation of LIKE v =, I had got myself running around in circles with GROUP BY.

    Warren


Bookmarks

Posting Permissions

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