我试图在表格中插入几行。这些行的几乎所有值都与同一个表中的另一组记录匹配,所以我很好奇我是否可以编写一个带有多个SELECT语句的INSERT语句来插入多行。像这样:
INSERT INTO table (col1, col2, col3, col4)
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 0
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 1
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 2
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 3
这可能吗?最后,它应该插入4行,所有行都具有相同的NewRecordID,col4值为0-3,而其他col值取自同一表上相应的OldRecordID。当我运行它时,它只运行第一个INSERT SELECT语句,然后将其他语句作为自己的SELECT语句运行。我错过了连接这些东西的东西吗?我总是可以多次运行它并每次更改值,但我想知道是否有办法避免这种情况。我很感激,帮助或有用的提示。
由于
答案 0 :(得分:1)
INSERT INTO table (col1, col2, col3, col4)
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 IN(0,1,2,3)
答案 1 :(得分:0)
您可以将Union连接到一个记录集:
INSERT INTO table (col1, col2, col3, col4)
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 0
union
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 1
union
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 2
union
SELECT (newRecordID, col2, col3, col4)
FROM table WHERE col1 = oldRecordID AND col4 = 3