关于mysql:在已按值过滤的数据库子集中随机选择行

Random row selection within a subset of a database which has been filtered by a value

目前我有一个名为 \\'images\\' 的数据库,我根据 RAND() 和 ORDER 随机选择 2 行。

1
2
3
4
5
6
$query="SELECT * FROM images ORDER BY RAND() LIMIT 0,2";
$result = @mysql_query($query);

while($row = mysql_fetch_object($result)) {
     $images[] = (object) $row;
}

这工作正常。但是,我想随机选择一行(randomrow1),然后通过 score > (randomrow1$score - 100) 创建图像数据库过滤器的子集


首先,首先要更改您的原始代码,以便只得到一个答案。

1
2
3
$query="SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result = @mysql_query($query);
$image = (object) mysql_fetch_object($result)

然后您需要提取分数,这将通过获取唯一图像对象的分数来完成,例如

1
2
$score1 = $image["score"]
$id1 = $image["id"]

那你就得再次查询:

1
2
3
$query="SELECT * FROM images WHERE score < #{$score1} + 100 AND score > #{$score1} - 100 AND id != #{$id1} ORDER BY RAND() LIMIT 1"
$result = @mysql_query($query)
$image2 = (object) mysql_fetch_object($result)

我的语法可能有点生疏,但这个通用答案应该适合你。