Select less than an id

Discussion in 'MySQL' started by Silver89, Apr 16, 2011.

  1. #1
    If I have a 1,000 items in a table and I want to get a random number ..

    $randnumber = '700';

    How could I select items:

    700,699,698,697,696

    from the table with 1 query that isn't where id='', is this possible? I was trying less than but it gets 1,2,3,4,5..
     
    Silver89, Apr 16, 2011 IP
  2. Alastair Gilfillan

    Alastair Gilfillan Active Member

    Messages:
    120
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #2
    SELECT * FROM table ORDER BY RAND() LIMIT 5
    Code (markup):
    Like that?
     
    Alastair Gilfillan, Apr 17, 2011 IP
  3. Silver89

    Silver89 Notable Member

    Messages:
    2,243
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    205
    #3
    Yes, but the table has over 100,000 rows so I'm trying to do it in a way that won't put as high a load in the processor?
     
    Silver89, Apr 17, 2011 IP
  4. Alastair Gilfillan

    Alastair Gilfillan Active Member

    Messages:
    120
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #4
    PHP, then.

    <?php
    $row_count = mysql_num_rows(mysql_query("SELECT * FROM table")); //unless you want to hard-code the number
    $random_row_number = rand(1, $row_count);
    $random_row = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE id=$random_row_number"));
    ?>
    Code (markup):
    Loop that or pre-fill an array with as many rows as you want to retrieve. That's the simplest solution I can come up with quickly. :)
     
    Alastair Gilfillan, Apr 17, 2011 IP
  5. AstarothSolutions

    AstarothSolutions Peon

    Messages:
    2,680
    Likes Received:
    77
    Best Answers:
    0
    Trophy Points:
    0
    #5
    SELECT * FROM table
    Code (markup):
    This is going to create a lot of data flowing, all 100,000 rows being returned every time.

    Is your ID column a sequential number? If it is then
    SELECT Max(RowID) FROM TableName;
    Code (markup):
    would be much better. You can then use the code to do the randomisation and then select those X rows. Alternative create a stored procedure that does the same.
     
    AstarothSolutions, Apr 18, 2011 IP
  6. Alastair Gilfillan

    Alastair Gilfillan Active Member

    Messages:
    120
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #6
    Thanks for that. I was going to write SELECT id but wasn't sure of the field names. I should have mentioned that because that's potentially a LOT of data haha.
     
    Alastair Gilfillan, Apr 19, 2011 IP