[英]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. 我知道SQL中的RAND()
函数从表中选择随机行,但是问题是我不希望它每次刷新浏览器时都选择不同的随机行。 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. 也许如果键是6,则每次都会选择第4行和第5行。 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. 但是,如果键是3,则它将选择行2和5。因此,每次它将基于键选择一组随机行。
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. 您可以使用MySQL函数的:Rand(N)形式,并在每次需要相同的生成随机数序列时注意传递相同的N。 The N could stay the same during a specific session or it could be stored in a cookie for use over a longer period. N可以在特定会话期间保持不变,也可以将其存储在cookie中以供较长时间使用。 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. 对md5哈希有很好的想法,但是有一种更简单的方法可以做到这一点。 Generate your random number however you want and the use the $_SESSION
superglobal to store the number. 根据需要生成您的随机数,并使用$_SESSION
超全局变量来存储该数字。
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: 使用PDO,会像这样:
$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, 将行ID保存在SESSION / Cookie中,
$var = value from $_SESSION/cookie
if (isset($var)){
$sql = select RAND...
} else {
$sql = select ..... where row = $var
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.