select 来自 table 的随机行

select a random rows from table

我有两个table一个叫做topic,如下图!
topic_id topic_name
1 主题 1
2 主题 2
3 主题 3

和另一个 table 调用的问题如图所示
q_id question_name topic_id
1 问题 1 1
2 问题 2 1
3 问题 3 1
4 问题 4 2
5 问题 5 2
6 问题 6 2
7 问题 7 3
8 问题 8 3
9 问题 9 3

我想从给定的三个主题中随机选择 2 个问题。有人请帮我解决这个问题

一个可以sort the rows randomly and then fetch the top row from this random order

对于 可能具有相同主题的两个随机问题

SELECT * FROM questions 
ORDER BY RAND() 
LIMIT 2

两个随机问题应该不同的主题: 使用 2 个不同的查询,将两个不同的 topic_ids (t1, t2):

作为参数

首先select 2个随机主题id(类似于上面的代码):

SELECT topic_id FROM topics 
ORDER BY RAND() 
LIMIT 2

然后 select 2 个带有这些主题 ID 的随机问题(2 select 语句)

SELECT * FROM questions 
WHERE topic_id = t1
ORDER BY RAND() 
LIMIT 1

SELECT * FROM questions 
WHERE topic_id = t2
ORDER BY RAND() 
LIMIT 1

更新(在 OP 的评论和解释之后)

要从每个主题中获得两个随机问题,请使用上述解决方案的变体:

3 select 个陈述(每个主题一个):

SELECT * FROM questions 
WHERE topic_id = needed_topic_id_here
ORDER BY RAND() 
LIMIT 2

对每个 topic_id 重复 select。

大概这些 select 语句可以合并成一个大的 select 语句,但我现在不确定。

注意 正如 中指出的那样,这可能效率较低(在纯 sql 中随机 select)并且更好解决方案是预先计算 PHP(或任何您的平台)中的随机索引,然后 then 实际上是 select 随机问题。由于问题中没有提到任何语言,我会把它留在这里(并指出这种方法的其他答案)

提供3个主题id随机抽取2个问题:

select q.question_name from topics t, questions q where t.topic_id = q.topic_id and t.topic_id in (1, 2, 3) /*define your 3 given topics*/ order by rand() limit 0,2;

获取主题列表及其问题 ID GROUP_CONCAT([column] order by RAND())。 然后 link table 到它自己。

SELECT t.q_id, t.question_name, t.topic_id
FROM table t
JOIN (
    SELECT topic_id, SUBSTRING_INDEX(GROUP_CONCAT(q_id ORDER BY RAND()), ',', 2) as qList
    FROM table GROUP BY topic_id
) tGrouped ON FIND_IN_SET(t.q_id, tGrouped.qList)>0

您可以在查询中使用 ORDER BY RAND()LIMIT 2,但对于 table 具有数千条或更多记录的查询,它 运行 的速度非常慢。

对于大 tables 更好的方法是使用您需要的 WHERE 条件获取 PK 字段的边界值,在这些边界值之间生成更小的 2 个随机数在 PHP 中然后发出 2 MySQL 个查询以获得 2 个问题。

大致如下:

$query = '
    SELECT MIN(q_id) AS min_id, MAX(q_id) AS max_id
    FROM questions
    WHERE topic_id = 1        # put the filtering you need here
';
// Run the query
// ... use your regular PHP code for database access here ...
// get and store the returned values in PHP variables $minId and $maxId


// Keep the generated random values here to avoid duplicates
$list = array();

// Get N random questions from the database
for ($cnt = 0; $cnt < N; $cnt ++) {
    // Generate a new ID that is not in the list
    do {
        $id = rand($minId, $maxId);
    } while (in_array($id, $list);

    // Put it into the list to avoid generating it again
    $list[] = $id;

    // Get the random question
    $query = "
        SELECT *
        FROM questions
        WHERE topic_id = 1
          AND q_id <= $id
        ORDER BY q_id DESC
        LIMIT 1
    ";
    // Run the query, get the question
    // ... use your regular PHP code for database access here ...
}

无论您 运行 查询什么(这些或其他答案提供的其他查询),您都需要 q_idWHERE 子句中使用的列的索引。

我希望 q_id 是 table 的 PK 这意味着它已经是 UNIQUE INDEX.