如何进行具有选择的多次插入

发布于 2024-11-07 03:14:42 字数 380 浏览 0 评论 0原文

如何插入必须从 select 语句获取信息的多个值或记录。这是行不通的。

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 username='ken',
 SELECT id FROM women WHERE username='barbie'))

假设我有表:

男人(id,姓名),女人(id,姓名),情侣(id,男,女)

等。

谢谢, 担

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 username='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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一萌ing 2024-11-14 03:14:42
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' )

添加

在评论中,您具体询问了原始查询的问题。首先,您可以像这样使用原始方法:

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

请注意,每个值都作为其自己的封装子查询括在括号中。其次,请注意,我使用了 Union All 指令来堆叠两个查询并给出两行。第三,请注意,我并没有尝试将 Values 指令与子查询结合使用。您可以使用 Values 子句列出值,也可以使用 Select 语句,但不能同时使用两者。显然,这种四个子查询的方法性能不佳,但它有助于理解语法的细分。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文