Simon Appelt
Simon Appelt

Reputation: 305

MySQL insert random values from another table

Hi I want to inserting some random values from one table to another my query looks like that:

INSERT INTO `rounds`(`matchID`, `questionOneID`, `questionTwoID`, `questionThreeID`) VALUES (17,(SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 3))

The problem is, that mysql wants 4 parameter (matchID, questionOneID,...) and only gets two (17,(...)) how do I tell MySql that it gets 3 parameters from the SELECT? Did i really have to:

INSERT INTO `rounds`(`matchID`, `questionOneID`, `questionTwoID`, `questionThreeID`) VALUES (17,(SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 1),(SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 1),(SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 1))

or is there a better way?

Upvotes: 2

Views: 1865

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269953

Your query looks correct. I would write it with insert . . . select:

INSERT INTO `rounds`(`matchID`, `questionOneID`, `questionTwoID`, `questionThreeID`)
     SELECT 17,
            (SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 1),
            (SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 1),
            (SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 1);

If you want to guarantee that the three questions are different, then I might go for this approach instead:

INSERT INTO `rounds`(`matchID`, `questionOneID`, `questionTwoID`, `questionThreeID`)
    SELECT 17,
           substring_index(group_concat(id order by rnd), ',', 1),
           substring(substring_index(group_concat(id order by rnd), ',', 2), ',', 11),
           substring_index(group_concat(id order by rnd), ',', -1),
    FROM (SELECT id, rand() as rnd FROM questions ORDER BY RAND() LIMIT 3) q

This will put three random questions on one row, with no duplicates (unless id is duplicated in questions.

Upvotes: 3

Related Questions