插入多个子查询作为值

时间:2012-06-05 16:19:27

标签: sql sql-server sql-server-2005

让我假设我要插入一个包含很多fk的表格,只是在下面解释一下错误的陈述

insert into mytable
values
(
somevalue
,somevalue
,select id from othertable1 where ...condition
,select id from othertable2 where ...condition
,select id from othertable3 where ...condition
)

所以基本上要插入的值来自不同的子查询,是否有可能实现这样的行为?

2 个答案:

答案 0 :(得分:9)

insert into mytable (columns)
select somevalue, somevalue, a.id, b.id, c.id
from
 othertable1 a
 cross join othertable2 b
 cross join othertable3 c
where
 a ... condition
 b ... condition
 c ... condition

答案 1 :(得分:1)

您可以使用select语句进行插入吗?

INSERT INTO MYTABLE
SELECT (SOMEVALUE,
    SOMEVALUE,
    T1.ID,
    T2.ID
)
FROM ANOTHERTABLE T1
JOIN YETANOTHERTABLE T2
    ON T1.BLAH = T2.BLAH
WHERE condition1...