2

我将如何选择 3 个问题 ID 并将它们用作单个插入语句的列数据,仅使用 MySQL。

我目前使用以下语句通过从问题表中选择一个随机条目将新行插入到游戏表中:

当前表:

 -------------------------------
| game | user_id | question_id |
 -------------------------------
| 1    | 1       | 10          |

当前声明:

INSERT INTO game (user_id, question_id)
 SELECT u.id as user_id, q.id as question_id
 FROM user u, question q
 WHERE u.id =:uid
 AND q.category = :category
 ORDER BY RAND()
 LIMIT 1

游戏桌: 我添加了 opt_1-3 列以允许多选

 -------------------------------------------------------
| game | user_id | question_id | opt_1 | opt_2 | opt_3 |
 -------------------------------------------------------
| 1    | 1       | 10          | 5     | 12    | 80    |
                                 ^       ^       ^
                               alternative wrong answers

我可以使用 PHP 来实现这一点,迭代结果并使用两个查询。

SELECT id FROM question
WHERE category = :category
ORDER BY RAND()
LIMIT 3

$opts = array();
foreach($result as $r){
    $opts[] = $r->id;
}

INSERT INTO game (user_id, question_id)
 SELECT u.id as user_id, q.id as question_id, 
 // add the following line to the query posted previously
 $opt[0] AS opt_1,  $opt[1] AS opt_2,  $opt[2] AS opt_3
 ... 

我想知道纯粹使用 MySQL 是否有可能达到相同的结果。

4

1 回答 1

1

没有测试这么多,但这可能会为你做选择。

请注意,通过 rand() 进行排序并不快,这涉及到几个交叉连接,如果有大量问题,这也可能会很慢。

SELECT u.id as user_id, Sub1.aid, Sub1.bid, Sub1.cid
FROM user u, 
(SELECT a.id AS aid, b.id AS bid, c.id AS cid
FROM question a, question b, question c
WHERE a.category = :category
AND a.category = :category
AND a.category = :category
AND a.id != b.id
AND a.id != c.id
AND b.id != c.id
ORDER BY RAND()
LIMIT 1) Sub1
WHERE u.id =:uid
于 2013-02-18T16:19:12.090 回答