2013-02-18 46 views
2

如何選擇3個問題ID並將它們用作單個插入語句的列數據,僅使用MySQL。使用子查詢行作爲列的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

沒有測試過這麼多,但這可能會爲您做選擇。

請注意,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 
+0

工作!我一直在試着用這樣的表述整天,但是我不能完全理解它,並且不會像預期的那樣工作。 (甚至開始看樞軸!:/)我已經讀了一些關於RAND()緩慢以及如何優化的內容,但在構建和測試時,它現在就足夠了。謝謝:) – TerryProbert 2013-02-18 16:33:32

+1

很高興幫助。像這樣的事情讓我覺得有點。 – Kickstart 2013-02-18 16:34:45