mysql - 多行插入语句包含相同的选择字段

标签 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)...

如何插入此选择结果而不执行每个记录?

谢谢

最佳答案

您应该为此使用变量:

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)...

关于mysql - 多行插入语句包含相同的选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855166/

相关文章:

php - 查询连接 id 匹配且行存在的表

python - 无法在通过python建立的tcp套接字上使用原始数据包处理mysql登录?可能是因为盐的原因?

mysql - 在 node.js 上使用 coalesce 和 sequelize

php - 从站点运行时查询给出不同的结果

sql - IO 错误 : The Network Adapter could not establish the connection - with Oracle 11gR2. 与 SQL 开发人员连接

sql - 查询检索具有空值的列

mysql - 是否可以在 MySQL 中执行这样的子查询?

mysql - Rails - 如何强制关联使用别名表名

sql - 在VBA过程中使用ADODB查询Excel文件时,多个JOIN不可用吗?

sql - 为什么不能在下一个 SELECT 表达式中使用列别名?