php Mysql 1 随机行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4938871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:18:28  来源:igfitidea点击:

Mysql 1 Random Row

phpmysql

提问by AndrewFerrara

Possible Duplicate:
How to request a random row in SQL?

可能的重复:
如何在 SQL 中请求随机行?

Is this the correct way to do this?

这是正确的方法吗?

$query = 'SELECT * FROM gameids ORDER BY timestamp RAND LIMIT 1';

回答by Marwelln

Incorrect. You cant order by a column (afaik) if you want it to randomize.

不正确。如果您希望它随机化,则不能按列(afaik)订购。

$query = 'SELECT * FROM gameids ORDER BY RAND() LIMIT 1';

回答by Alan Whitelaw

You don't need to tell it which column to randomise, but you do need ()after RANDbecause it is a function.

您不需要告诉它随机化哪一列,但您确实需要()afterRAND因为它是一个函数。

SELECT
  * 
FROM
  gameids 
ORDER BY 
  RAND()
LIMIT 1

回答by ludesign

RAND is a function and its not effective in big tables, because it does not use indexes.

RAND 是一个函数,它在大表中无效,因为它不使用索引。

$query = 'SELECT * FROM gameids ORDER BY RAND() LIMIT 1';

One possible solution is to add column called randomand on every record generate random number for it, then when you are querying the database, order by this column and you'll get pseudo-random but this time using the indexes.

一种可能的解决方案是添加被调用的列random并在每条记录上为其生成随机数,然后当您查询数据库时,按此列排序,您将获得伪随机,但这次使用索引。

$query = 'SELECT * FROM gameids ORDER BY timestamp, random LIMIT 1';

Edit: You can also make RAND()more "flexible" by applying some expression like this RAND() * MAX(numeric_column_name)

编辑:您还可以RAND()通过应用这样的一些表达式来使其更加“灵活”RAND() * MAX(numeric_column_name)

If you are interested in optimizations, take a look at this blog post: http://jan.kneschke.de/projects/mysql/order-by-rand/

如果您对优化感兴趣,请查看此博客文章:http: //jan.kneschke.de/projects/mysql/order-by-rand/

@Marwelln is correct.

@Marwelln 是正确的。