Need help with a SQL query

Discussion in 'Programming' started by ImpulseHorizon, Mar 23, 2008.

  1. #1
    Ok, a have an SQL db with 10000 keywords. I need to create a random list of 100 keywords, but the way I am doing it now is taking up too much cpu time. So I want to generate 1 random number and then take the next next 99 keywords that are right after it instead of it all being randomized. I think that will take up less CPU.

    I'm not sure what the query should be and how to do the code. Each keyword in the db is also numbered 1-10000 by column Id. So I want it to get keywords starting with random number X and then X+1 for the the next 99 queries... and put that into the array.

    Here is the original code:

    $this->random = $this->getRandomKeywords(100);

    function getRandomKeywords($number) {
    $results = array();
    $query = "SELECT keyword FROM list ORDER BY RAND() LIMIT ".$number;
    $this->db->query($query);
    while($this->db->nextRecord()) {
    $results[] = $this->db->record[0];
    }
    return $results;
    }
     
    ImpulseHorizon, Mar 23, 2008 IP
  2. ImpulseHorizon

    ImpulseHorizon Peon

    Messages:
    43
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I solved it, takes no cpu:

    $rand2 = rand(1, 9900);
    $query = "SELECT keyword FROM 365k WHERE Id > '".$rand2."' LIMIT ".$number;
     
    ImpulseHorizon, Mar 23, 2008 IP
  3. TomK32

    TomK32 Peon

    Messages:
    113
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can select more than one result from the database with IN.
    SELECT keyword FROM 365k WHERE Id IN (123,2341,133,425,23,345,234,12);
     
    TomK32, Mar 24, 2008 IP
  4. ausome

    ausome Peon

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    This might be useful, though I've not tried it on a 10,000 Row Table

    $query = sprintf("SELECT %s FROM %s ORDER BY RAND() LIMIT %d",$field_name,$table_name,$number);
     
    ausome, Mar 26, 2008 IP