开发者

How do you do multiple inserts that have selects

开发者 https://www.devze.com 2023-03-06 02:36 出处:网络
How do I do an insert multiple values or records that have to get their information from select statements.This doesn\'t work.

How do I do an insert multiple values or records that have to get their information from select statements. This doesn't work.

INSERT INTO marriedcouples (male,female) VALUES (
(SELECT id FROM men WHERE username='brad',
 SELECT id FROM women WHERE username='jennifer')
(SELECT id FROM men WHERE user开发者_如何学Pythonname='ken',
 SELECT id FROM women WHERE username='barbie'))

Assuming I have tables with:

men(id,name), women(id,name), couples(id,male,female)

etc.

Thanks, Dan


Insert marriedcouples( male, female )
Select M.id, W.id
From Men As M
    Cross Join Women As W
Where ( M.username = 'brad' And W.username = 'jennifer' )
    Or ( M.username = 'ken' And W.username = 'barbie' )

Addition

In comments, you asked specifically about the problems with your original query. First, you could have used your original approach like so:

Insert marriedcouples( male, female )
Select ( Select Id From men Where username = 'brad' )
    , ( Select Id From women Where username = 'jennifer' )
Union All
Select ( Select Id From men Where username = 'ken' )
    , ( Select Id From women Where username = 'barbie' )

Notice that each value is enclosed in parentheses as its own encapsulated subquery. Second, notice that I used the Union All directive to allow me to stack the two queries and give me two rows. Third, notice that I'm not trying to use the Values directive in combination with subqueries. You can use the Values clause to list out values or you can use a Select statement but not both in the way you did. Obviously, this approach of four subqueries will not perform well but it helps to understand the breakdown of the syntax.

0

精彩评论

暂无评论...
验证码 换一张
取 消