Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In MySQL, it's probably easiest to do this in two queries. First, get the count of rows in the table:</p> <pre><code>SELECT COUNT(*) FROM MyTable; </code></pre> <p>Then prepare the query to get random rows:</p> <pre><code>SELECT ... FROM MyTable ORDER BY RAND() LIMIT ?; </code></pre> <p>Then execute the prepared query and send the value of the count divided by 10.</p> <p>Not every problem needs to be solved by a single query.</p> <hr> <p>Here's an example PHP script, edited to use the old mysql extension.</p> <pre><code>&lt;?php // Get the total number of rows in the table. $sql = "SELECT COUNT(*) FROM Kingdoms"; $result = mysql_query($sql); $row = mysql_fetch_array($result); $rows_in_table = $row[0]; // We only want a portion of the rows, specified by the user // choice of percentage. The count we want is therefore equal // to the total number of rows in the table multiplied by the // desired percentage. $percentage = intval($_GET["percentage"]) / 100.0; $count = intval(round($rows_in_table * $percentage)); // LIMIT makes the query return at most the number of rows specified. // Sort randomly first (if the table has too many rows this will be slow), // then return the first $count rows. $sql = "SELECT * FROM Kingdoms ORDER BY RAND() LIMIT {$count}"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result)) { print_r($row); } </code></pre> <p>PS: Always be careful when interpolating a variable into an SQL expression. You should force the variable to a known format -- an integer value in this case. Otherwise you risk creating an SQL Injection vulnerability.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload