Need Help Fast: SELECT DISTINCT query

Discussion in 'PHP' started by goscript, Jun 7, 2007.

  1. #1
    I'm having the following table:

    Table paragraph
    ID | text | number
    _________________
    1|text1|1
    2|text2|1
    3|text3|1
    4|text4|2
    5|text5|2
    6|text6|3
    7|text7|3
    8|text8|3
    9|text9|3

    I need to select 3 random rows that have DISTINCT number.

    I have tried something like
    SELECT id,text,number FROM paragraph WHERE number = DISTINCT ORDER BY rand() LIMIT 3
    PHP:
    , but it gives errors.

    Anyone willing to help?
    Thanks
     
    goscript, Jun 7, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    SELECT DISTINCT number, id, text, number FROM paragraph ORDER BY rand() LIMIT 3
    
    Code (sql):
    Try this.
     
    nico_swd, Jun 7, 2007 IP
    goscript likes this.
  3. goscript

    goscript Prominent Member

    Messages:
    2,753
    Likes Received:
    306
    Best Answers:
    0
    Trophy Points:
    315
    #3
    Thanks, it seems to work, but i think there is a problem with the rand() , as it returns always the same 3 numbers.
    It returns different rows but from the same numbers.
     
    goscript, Jun 7, 2007 IP
  4. goscript

    goscript Prominent Member

    Messages:
    2,753
    Likes Received:
    306
    Best Answers:
    0
    Trophy Points:
    315
    #4
    OK, i fixed it. All i had to do is replace rand() with rand(NOW())

    Thanks.
     
    goscript, Jun 7, 2007 IP
  5. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #5
    in the long run it's faster to just select the distinct id's and then get the random generated ones via PHP then re-query the database to get the ones that were selected. less overhead that way looking from a performance standpoint. of course with only a result set of 3 rows it really wouldn't matter but just for future reference.
     
    ansi, Jun 7, 2007 IP