MySQL 将 GROUP BY 结果插入另一个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1753221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting a GROUP BY result into another table
提问by jerrygarciuh
I was migrating a field to a new table. The new table has three fields. What I tried was
我正在将一个字段迁移到一个新表。新表具有三个字段。我试过的是
INSERT INTO foo VALUES ('', (SELECT bar FROM baz GROUP BY bar), '');
This resulted in an error due to multiple rows resulting from the select.
由于选择导致多行,这导致错误。
What is the right way to do this?
这样做的正确方法是什么?
回答by Michael Petrotta
If I understand you correctly, you want something like:
如果我理解正确,你想要的是:
INSERT INTO foo (col1name, col2name, col3name)
SELECT '', bar, ''
FROM baz
GROUP BY bar
回答by MadMurf
Or if I'm understanding you correctly and you want one entry in the new table for every distinct bar value in the old table I think this makes that a bit clearer.
或者,如果我对您的理解是正确的,并且您希望旧表中每个不同的条形值在新表中都有一个条目,我认为这会使这更清楚一些。
INSERT INTO foo (col2name) SELECT DISTINCT bar FROM baz
The execution plan and performance should be similiar
执行计划和性能应该相似
回答by LukLed
You can try:
你可以试试:
INSERT INTO foo
SELECT '',bar,'' FROM baz GROUP BY bar
回答by spender
INSERT INTO foo (fieldName1,fieldName2,fieldName3)
SELECT '',bar,'' FROM baz GROUP BY bar
回答by Carl Smotricz
Going with Michael's answer, another possibility would be
按照迈克尔的回答,另一种可能性是
INSERT INTO foo (col2name) SELECT bar FROM baz GROUP BY bar
where col1 and col3 are defined to have a default of the empty string.
其中 col1 和 col3 被定义为默认为空字符串。