简体   繁体   中英

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?

Your query looks correct. I would write it with insert . . . select insert . . . select 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM