从mysql查询中打印随机行 [英] Print a random row from a mysql query
问题描述
我一直在寻找一种创建协作翻译小部件的方法.因此,我有一个mysql数据库和表(称为翻译),还有一个小脚本,允许用户一次翻译一页.
I was looking for a way of creating a collaborative translation widget. So I have a mysql database and table (called translations), and a little script to allow users to translate one page at a time.
但是我对我的脚本不太满意.我认为效率不够高.首先,mysql获取所有带有"en"列为空的行,然后在一段时间内屏幕上仅显示其中的一行.还有其他方法吗?这是代码:
But I'm not quite convinced with my script. I don't think it's efficient enough. First, the mysql gets all the rows with the empty 'en' column, and then a single one of them is showed by screen through a while. Is there any other way of doing this? This is the code:
//Retrieve all the data from the "translations" table
$result = mysql_query("SELECT * FROM translations WHERE en IS NULL OR en=''") or die(mysql_error());
$Randnum=rand(0,mysql_num_rows($result)-1); //Gets a random number between 0 and the maximum number of rows
$i=0; //Start to 0
while($Col = mysql_fetch_array($result)) //While there are rows to evaluate
{
if ($i==$Randnum)
{
echo "\"".$Col['es']."\"<br><br>Translate it to English: <br>";
}
$i++;
}
我正在寻找类似"echo $ Col [$ Randnum] ['es']"或"echo $ Col. $ Randnum ['es']"之类的东西,而不是使用整个while循环来打印单个随机行.我该如何实现呢?如果只是优化问题.如果您可以提供一个脚本或一个想法来将$ Col仅分配给一个带有随机数和空的'en'col的行,那就更好了! (我认为这最后一点是不可能的). "en"行是文本,因此我不知道如何实现其他方法我发现他们在ORDER BY上使用数字.
I was looking for something like "echo $Col[$Randnum]['es']" or "echo $Col.$Randnum['es']" instead of using the whole while loop to print a single random row. How can I implement this? If it's just a matter of optimization. If you could come with an script or idea to assign to $Col just ONE row with a random number and the empty 'en' col, that'd be even better! (I think it's not possible this last bit). The 'en' row is text so I don't know how to implement other methods I've seen around as they use number with ORDER BY.
推荐答案
您可以在查询中使用ORDER BY RAND() LIMIT 1
从数据库中提取单个随机行.
You can use ORDER BY RAND() LIMIT 1
in your query to fetch a single random row from the database.
这篇关于从mysql查询中打印随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!