【发布时间】:2013-03-09 13:12:33
【问题描述】:
有没有办法插入预设值和我从选择查询中获得的值? 例如:
INSERT INTO table1 VALUES ("A string", 5, [int]).
我有“A string”的值和数字 5,但我必须从这样的选择中找到 [int] 值:
SELECT idTable2
FROM table2
WHERE ...
这给了我将 ID 放入 table1 中。
如何将其合并到一个语句中?
【问题讨论】:
有没有办法插入预设值和我从选择查询中获得的值? 例如:
INSERT INTO table1 VALUES ("A string", 5, [int]).
我有“A string”的值和数字 5,但我必须从这样的选择中找到 [int] 值:
SELECT idTable2
FROM table2
WHERE ...
这给了我将 ID 放入 table1 中。
如何将其合并到一个语句中?
【问题讨论】:
尝试以下方法:
INSERT INTO table1
SELECT 'A string', 5, idTable2 idTable2 FROM table2 WHERE ...
【讨论】:
使用insert ... select 查询,并将已知值放入select:
insert into table1
select 'A string', 5, idTable2
from table2
where ...
【讨论】:
SELECT 返回零记录,则语句成功但没有数据是INSERT。
只需在此处使用子查询,例如:
INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).
【讨论】:
VALUES 语法的同时执行此操作的示例。
试试这个:
INSERT INTO table1 SELECT "A string", 5, idTable2 FROM table2 WHERE ...
【讨论】:
INSERT INTO table1
SELECT "A string", 5, idTable2
FROM table2
WHERE ...
【讨论】:
INSERT INTO table1 (col1, col2)
SELECT "a string", 5, TheNameOfTheFieldInTable2
FROM table2 where ...
【讨论】:
试试这个
INSERT INTO TABLE1 (COL1 , COL2,COL3) values
('A STRING' , 5 , (select idTable2 from Table2) )
where ...
【讨论】:
SELECT 表中的多个列怎么样?如果我尝试不止一列来自那里,我会得到Operand should contain 1 column(s)。
所有其他答案都解决了这个问题,我的答案与其他答案的工作方式相同,但只是以更具教学性的方式(这适用于 MySQL...不知道其他 SQL 服务器):
INSERT INTO table1 SET
stringColumn = 'A String',
numericColumn = 5,
selectColumn = (SELECT idTable2 FROM table2 WHERE ...);
您可以参考 MySQL 文档:INSERT Syntax
【讨论】:
【讨论】:
INSERT INTO table1(Table2Id, KeyTypeEnumId, SortOrder, TenantId)
SELECT Id, 1, 1, TenantId
FROM table2
WHERE WebsitePageTypeEnumId = 10 AND ElementTypeEnumId = 16
【讨论】: