如何从PHP中的MySQL数据库中选择一个随机行?

时间:2022-11-24 22:41:50

I have a database table questions on a online web server with 2000+ rows and I need to get 6 randomly selected rows. They must be different so that one question is not two times in the list array of 6 questions.

我在具有2000多行的在线Web服务器上有一个数据库表问题,我需要随机选择6行。它们必须是不同的,因此在6个问题的列表数组中,一个问题不是两次。

How can I achieve this?

我怎样才能做到这一点?

2 个解决方案

#1


7  

You have a relatively small amount of data, so the simplest method is:

您的数据量相对较少,因此最简单的方法是:

select q.*
from questions q
order by rand()
limit 6;

In this query, the order by takes the longest amount of time. Ordering 2,000 rows might be noticeable. A simple fix is to reduce the number of rows being ordered. One method is:

在此查询中,订单时间最长。订购2,000行可能会引人注意。一个简单的解决方法是减少订购的行数。一种方法是:

select q.*
from questions q cross join
     (select count(*) as cnt from questions) m
where rand() < 100 / m.cnt
order by rand()
limit 6;

The where selects about 100 rows randomly and then orders those to select 6. You are pretty much guaranteed that the where will always choose at least 6 rows.

where随机选择大约100行然后命令那些选择6.你几乎可以肯定,where总是会选择至少6行。

#2


4  

Use the DISTINCT operator in MySQL:

在MySQL中使用DISTINCT运算符:

SELECT DISTINCT column FROM table ORDER BY RAND() LIMIT 6;

So DISTINCT will take care and remove duplicates

所以DISTINCT会照顾并删除重复项

#1


7  

You have a relatively small amount of data, so the simplest method is:

您的数据量相对较少,因此最简单的方法是:

select q.*
from questions q
order by rand()
limit 6;

In this query, the order by takes the longest amount of time. Ordering 2,000 rows might be noticeable. A simple fix is to reduce the number of rows being ordered. One method is:

在此查询中,订单时间最长。订购2,000行可能会引人注意。一个简单的解决方法是减少订购的行数。一种方法是:

select q.*
from questions q cross join
     (select count(*) as cnt from questions) m
where rand() < 100 / m.cnt
order by rand()
limit 6;

The where selects about 100 rows randomly and then orders those to select 6. You are pretty much guaranteed that the where will always choose at least 6 rows.

where随机选择大约100行然后命令那些选择6.你几乎可以肯定,where总是会选择至少6行。

#2


4  

Use the DISTINCT operator in MySQL:

在MySQL中使用DISTINCT运算符:

SELECT DISTINCT column FROM table ORDER BY RAND() LIMIT 6;

So DISTINCT will take care and remove duplicates

所以DISTINCT会照顾并删除重复项