简体   繁体   中英

How to select a set of random rows from a table based on a key?

I know about the RAND() function in SQL to select random rows from a table, but the problem is I don't want it selecting different random rows each time I refresh the browser. I want the same set of random rows, which is selected based on a key.

For example, say this is my table:

----------------------
| id | word | literal|
----------------------
|  1 | say  |   YAS  |
----------------------
|  2 | eat  |   TAE  |
----------------------
|  3 | hit  |   TIH  |
----------------------
|  4 | bad  |   DAB  |
----------------------
|  5 |delve | EVLED  |
----------------------

maybe if the key was 6, it would select rows 4 & 5 every time. But maybe if the key was 3, it would select rows 2 and 5. So it would select a set of random rows each time based on a key.

Is this possible?

You can use the : Rand(N) form of the MySQL function and take care to pass the same N each time you want the same sequence of generated random numbers. The N could stay the same during a specific session or it could be stored in a cookie for use over a longer period. It depends on how long you need the sequence to remain the same.

Good thought with the md5 hash, but there's a much easier way to do it. Generate your random number however you want and the use the $_SESSION superglobal to store the number.

Example:

session_start();
if(!isset($_SESSION["randomNumber"])){
    $_SESSION["randomNumber"] = generateRandomQuery();
}

You'd then be able to use the number when you build your query. Using PDO, it'd be like this:

$number = $_SESSION["randomNumber"];
$query = $database->prepare("SELECT id FROM *databaseName* where id = :id");
$query->execute(array(":id" => $number));

An idea..

Save the row id in SESSION/cookie,

$var = value from $_SESSION/cookie
if (isset($var)){

   $sql = select RAND...

} else {

   $sql = select ..... where row = $var

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM