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

前端 未结 2 652
执念已碎
执念已碎 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:26

    Adding your RAND() call into the ORDER BY clause should allow you to ignore the ID. Try this:

    SELECT * FROM table WHERE ... ORDER BY RAND() LIMIT 3;
    

    After having performance issues pointed out, your best bet may be something along these lines (utilizing PHP):

    $result = PDO:query('SELECT MAX(id) FROM table');
    $max    = $result->fetchColumn();
    $ids    = array();
    $rows   = 5;
    
    for ($i = 0; $i < $rows; $i++) {
        $ids[] = rand(1, $max);
    }
    
    $ids     = implode(', ', $ids);
    $query   = PDO::prepare('SELECT * FROM table WHERE id IN (:ids)');
    $results = $query->execute(array('ids' => $ids));
    

    At this point you should be able to select the first 3 results. The only issue with this approach is dealing with deleted rows and you might have to either bump the $rows var or add some logic to do another query in case you didn't receive at least 3 results back.

提交回复
热议问题