简体   繁体   English

INSERT INTO…SELECT带有更多SELECT列

[英]INSERT INTO … SELECT with more SELECT columns

Thank you for your time. 感谢您的时间。

I have a INSERT INTO ... SELECT setup, but I also want to filter using extra columns (that do not exist in the table I am inserting into) 我有一个INSERT INTO ... SELECT设置,但我也想使用多余的列进行过滤(在我要插入的表中不存在)

For example: 例如:

INSERT INTO table1 (t1_col1, t1_col2, t1_col3)
SELECT
  t2.t1_col1,
  t2.t1_col2,
  t3.t1_col3,
  t4.filter_col
FROM table2 t2
  INNER JOIN table3 t3 ON t2.t1_col1 = t3.t1_col1
  INNER JOIN table4 t4 ON t4.filter_col = t2.filer_col
WHERE t4.filter_col = 'value';

table1 only has columns t1_col1 , t1_col2 and t1_col3 so when I attempt to run this it fails as expected: table1仅具有t1_col1t1_col2t1_col3列,因此当我尝试运行此列 ,它按预期失败:

ERROR:  INSERT has more expressions than target columns

So my question is, how can I still include the filter, but specify which columns from my SELECT statement should be used in the INSERT INTO statement. 所以我的问题是,如何仍可以包括过滤器,但要指定SELECT语句中的哪些列应在INSERT INTO语句中使用。

Many thanks for any help! 非常感谢您的帮助!

you have to same number of column in select ,so remove t4.filter_col from selection 您必须在select中具有相同的列数,因此从选择中删除t4.filter_col

INSERT INTO table1 (t1_col1, t1_col2, t1_col3)
SELECT
  t2.t1_col1,
  t2.t1_col2,
  t3.t1_col3      
FROM table2 t2
  INNER JOIN table3 t3 ON t2.t1_col1 = t3.t1_col1
  INNER JOIN table4 t4 ON t4.filter_col = t2.filer_col
WHERE t4.filter_col = 'value';

Note: you are not bound to select all columns those you used in join or filter 注意:您不必选择在联接或过滤器中使用的所有列

It's almost right, but you select one column too much. 几乎是正确的,但是您选择了太多一列。 Try this: 尝试这个:

INSERT INTO table1 (t1_col1, t1_col2, t1_col3)
SELECT
  t2.t1_col1,
  t2.t1_col2,
  t3.t1_col3
FROM table2 t2
  INNER JOIN table3 t3 ON t2.t1_col1 = t3.t1_col1
  INNER JOIN table4 t4 ON t4.filter_col = t2.filer_col
WHERE t4.filter_col = 'value';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM