SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: How would I order RAND() selections?

  1. #1
    Formerly known as RockNRollPig Shpigford's Avatar
    Join Date
    Dec 2002
    Location
    Denver, CO
    Posts
    2,877
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How would I order RAND() selections?

    How would I go about alphabetizing random items from the database? For example, I have say 500 rows in my database. I want to randomly select 10 to display at any given time but I want to alphabetize them. How would I do that? I've tried the following which didn't really work at all:

    PHP Code:
    SELECT FROM nodes WHERE parentid='289814' ORDER BY RAND(),'name' LIMIT 0,10 

  2. #2
    SQL Consultant silver trophybronze trophy
    SitePoint Award Recipient r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    38,466
    Mentioned
    35 Post(s)
    Tagged
    1 Thread(s)
    since you need ORDER BY RAND() to do the randome selection, you will need to sort them by name some other way

    the best way would be:
    Code:
    select * 
      from (
           SELECT * FROM nodes 
            WHERE parentid='289814' 
           ORDER BY RAND()
           LIMIT 0,10 
           )
    order by name
    but of course mysql won't support that until 4.1 (sorry, can't test it for you, don't have 4.1 myself)

    you could use a temp table, or, since there are only 10 rows, sort them with your scripting language
    r937.com | rudy.ca | Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

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
  •