您好我想从一个表中插入一些随机值到另一个表我的查询看起来像这样:
INSERT INTO `rounds`(`matchID`, `questionOneID`, `questionTwoID`, `questionThreeID`) VALUES (17,(SELECT `id` FROM `questions` ORDER BY RAND() LIMIT 3))
问题是,mysql需要4个参数(matchID,questionOneID,...)并且只得到两个(17,(...))如何告诉MySql它从SELECT中获取3个参数? 我真的需要:
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))
还是有更好的方法吗?
答案 0 :(得分:3)
您的查询看起来是正确的。我会用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);
如果你想保证三个问题不同,那么我可能会选择这种方法:
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
这会在一行上放置三个随机问题,不会重复(id
除非questions
重复。