使用子查询行作为列的MySQL单插入

时间:2013-02-18 15:57:08

标签: php mysql

我如何选择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来实现相同的结果。

1 个答案:

答案 0 :(得分: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