如何进行具有选择的多次插入
如何插入必须从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加
在评论中,您具体询问了原始查询的问题。首先,您可以像这样使用原始方法:
请注意,每个值都作为其自己的封装子查询括在括号中。其次,请注意,我使用了 Union All 指令来堆叠两个查询并给出两行。第三,请注意,我并没有尝试将 Values 指令与子查询结合使用。您可以使用 Values 子句列出值,也可以使用 Select 语句,但不能同时使用两者。显然,这种四个子查询的方法性能不佳,但它有助于理解语法的细分。
Addition
In comments, you asked specifically about the problems with your original query. First, you could have used your original approach like so:
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.