Results 1 to 3 of 3

Thread: Select random row

  1. #1
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Select random row

    I have a table called funny that contains a lot of funny quotes. I would like to randomly display 1 on a page.I am doing this right now by loading them all into an array and shuffleing the array.Is their any way to do this with mysql? Here's my sql right now
    Code:
    SELECT data FROM funny WHERE funny.set = 'general'
    I'm not very good with sql so any help would be great.

  2. #2
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by blm126
    I would like to randomly display 1 [result] on a page.I am doing this right now by loading them all into an array and shuffleing the array.Is their any way to do this with mysql?
    MySQL implements many extensions to the SQL standard (I'd prefer that they finish implementing SQL though, personally), one of which is ordering based on an expression. The rand function can be used to obtain a random order, and the limit clause can speed up the query, as well as reduce the amount of data to transfer:

    SELECT data FROM funny WHERE funny.set='general' ORDER BY RAND() LIMIT 1

    Be aware that the above is untested, and if you were to move to another DBMS (like PostgreSQL, for instance), this query is likely to fail.

    Mike

  3. #3
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default

    Thanks that worked perfectly

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
  •