Results 1 to 3 of 3

Thread: Help with displaying random records with MySQL

Hybrid View

  1. #1
    Join Date
    Mar 2008

    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
    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.)
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

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

    select * from
    (SELECT ID, 	Job, 	Category
    FROM employee
    union all
    SELECT ID, 	Job, 	Category
    FROM employee)
    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