www.webdeveloper.com
Results 1 to 3 of 3

Thread: Help with displaying random records with MySQL

  1. #1
    Join Date
    Mar 2008
    Posts
    2

    Help with displaying random records with MySQL

    I have the following table:
    ID Job Category
    1 Clerk Admin
    2 Secretary Admin
    3 Reception Admin
    4 Typist Admin

    Now, I want to display 5 jobs within the Admin Category, but I want them pulled randomly from the database. ORDER BY RAND won't work because there are only 4 records. I need to display 5 records as it doesn't matter if the same record is displayed more than once. How do I do this?

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,178
    I'd probably just loop through the result set as usual, but keep a counter of records displayed. Then if the counter is less than 5, reset the result pointer back to the first record, and start cycling through it again until the counter reaches 5. (Of course, check for 0 results first, so you don't get into an infinite loop.)
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Sep 2011
    Posts
    59
    try something like that

    Code:
    select * from
    (SELECT ID, 	Job, 	Category
    FROM employee
    union all
    SELECT ID, 	Job, 	Category
    FROM employee)
    ORDER BY RAND()
    LIMIT 5

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles