[英]Select Random yet distinct rows from table - MySQL
I have a table with various categories, and multiple entries for each category. 我有一个包含各种类别的表,每个类别有多个条目。
Word | Category
------------------
Apple | Food
Orange | Food
Grapes | Food
Mango | Food
I wish to retrieve 3 random rows for the category 'food', for which I run the following query, 我希望为“食品”类别检索3个随机行,为此我运行了以下查询,
$query = "SELECT * FROM table WHERE category='food' ORDER BY RAND() LIMIT 3"
$fetch_row = mysqli_query($db_connect, $query);
while ($row = mysqli_fetch_array($fetch_row)) {
array_push($words, $row['word']);
}
However, when I print the contents of the array $words, they tend to repeat sometimes (not on all runs), for example; 但是,当我打印$ word数组的内容时,例如,它们有时有时会重复(并非在所有运行中都重复);
Apple, Orange, Apple
苹果,橙,苹果
ie Its not always unique. 即它并不总是唯一的。 I want to select random, yet unique words for a given category.
我想为给定类别选择随机但独特的单词。 What am I doing wrong?
我究竟做错了什么? I've tried going through other related answers, but I keep messing something up.
我尝试过其他相关的答案,但是我一直在弄乱一些东西。 I've also tried the following query;
我也尝试了以下查询;
SELECT * FROM table WHERE category='food' GROUP BY category ORDER BY RAND() LIMIT 3
But this still gives repetitions occasionally. 但这偶尔仍会重复。
由于word
列具有相同的值,因此请按以下方式对GROUP BY word
分组:
SELECT * FROM table WHERE category='food' GROUP BY word LIMIT 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.