我将如何选择 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 是否有可能达到相同的结果。