简体   繁体   English

获取随机查询结果,然后对其进行排序

[英]get a random query result and then sort it

I need to run an ORDER BY RAND query and then sort the resulting data set numerically. 我需要运行ORDER BY RAND查询,然后对所得数据集进行数字排序。 In other words I want a random set of data (in this case 7 numbers), but then I need to sort those 7 results numerically. 换句话说,我想要一个随机的数据集(在这种情况下为7个数字),但是随后我需要对这7个结果进行数字排序。

After this code runs: 此代码运行后:

if ($today == "Oct 31") { 

  $dayList = "halloween"; 
  $stmt = $pdo->query("SELECT `rand` FROM `jukebox2014` 
           WHERE `class` = '$dayList' ORDER BY RAND() LIMIT 7");
}

I need to sort the 7 results. 我需要对7个结果进行排序。

Any ideas? 有任何想法吗?

Thanks. 谢谢。

As simple as: 简单如:

SELECT `rand`
FROM (
    SELECT ... ORDER BY RAND() LIMIT 7
)
ORDER BY `rand`

Not that ORDER BY RAND() LIMIT 7 is a rather inefficient method to select random data; 并不是说ORDER BY RAND() LIMIT 7是一种选择随机数据的效率很低的方法; more efficient methods will depend on your exact data. 更有效的方法将取决于您的确切数据。 Search Stackoverflow for many questions regarding this topic. 在Stackoverflow上搜索有关此主题的许多问题。

I think this is what you mean. 我想这就是你的意思。

$new = array();
foreach ($results as $result) {
    $new[] $result['rand'];
}

$sorted = ksort($new);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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