具有多行的Insert语句包括相同的选择字段

时间:2014-02-18 13:22:18

标签: mysql sql

我必须进行多次插入,但所有这些新记录都将具有从其他表中检索的相同字段:

INSERT INTO `user` (`id`, `name`, `surname`, `retrieved`) VALUES
(null, "A", "A", SELECT id from user_records where id = 1),
(null, "B", "B", SELECT id from user_records where id = 1),
(null, "C", "C", SELECT id from user_records where id = 1)...

如何在不执行每条记录的情况下插入此选择结果?

谢谢

2 个答案:

答案 0 :(得分:1)

你应该使用变量:

SET @VAR := SELECT id 
              FROM user_records 
             WHERE id = 1;

INSERT INTO `user` (`id`, `name`, `surname`, `retrieved`) 
VALUES
(null, "A", "A", @VAR),
(null, "B", "B", @VAR),
(null, "C", "C", @VAR)...

SELECT id INTO @VAR 
  FROM user_records 
 WHERE id = 1;

INSERT INTO `user` (`id`, `name`, `surname`, `retrieved`) 
VALUES
(null, "A", "A", @VAR),
(null, "B", "B", @VAR),
(null, "C", "C", @VAR)...

答案 1 :(得分:0)

首先,声明并指定var

DECLARE user_id INT;
SET user_id = (SELECT id from user_records where id = 1);

然后,在插入查询中使用var

INSERT INTO `user` (`id`, `name`, `surname`, `retrieved`) VALUES
(null, "A", "A", user_id),
(null, "B", "B", user_id),
(null, "C", "C", user_id)