MySQL: what's the most efficient way to select multiple random rows

前端 未结 2 650
执念已碎
执念已碎 2021-01-06 18:56

I have a fairly large dataset and a query that requires two joins, so efficiency of the query is very important to me. I need to retrieve 3 random rows from the database tha

2条回答
  •  情深已故
    2021-01-06 19:40

    Since you don't want many results, there are a couple of interesting options using LIMIT and OFFSET.

    I'm going to assume an id column which is unique and suitable for sorting.

    The first step is to execute a COUNT(id), and then select random 3 numbers from 0 to COUNT(id) - 1 in PHP. (How to do that is a separate question, and the best approach depends on the number of rows total and the number you want).

    The second step has two options. Suppose the random numbers you selected are 0, 15, 2234. Either have a loop in PHP

    // $offsets = array(0, 15, 2234);
    foreach ($offsets as $offset) {
        $rows[] = execute_sql('SELECT ... ORDER BY id LIMIT 1 OFFSET ?', $offset);
    }
    

    or build a UNION. Note: this requires sub-selects because we're using ORDER BY.

    // $offsets = array(0, 15, 2234);
    $query = '';
    foreach ($offsets as $index => $offset) {
        if ($query) $query .= ' UNION ';
        $query .= 'SELECT * FROM (SELECT ... ORDER BY id LIMIT 1 OFFSET ?) Sub'.$index;
    }
    $rows = execute_sql($query, $offsets);
    

提交回复
热议问题