簡體   English   中英

使用子查詢行作為列的MySQL單插入

[英]MySQL single insert using subquery rows as columns

我將如何選擇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即可達到相同的結果。

沒有經過太多測試,但這可能會為您做選擇。

請注意,通過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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM