【问题标题】:INSERT INTO ... SELECT with more SELECT columnsINSERT INTO ... SELECT 具有更多 SELECT 列
【发布时间】:2019-03-14 00:11:57
【问题描述】:

感谢您的宝贵时间。

我有一个 INSERT INTO ... SELECT 设置,但我还想使用额外的列进行过滤(我要插入的表中不存在这些列)

例如:

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 只有列 t1_col1t1_col2t1_col3 所以当我尝试运行它时它失败了预期:

ERROR:  INSERT has more expressions than target columns

所以我的问题是,我怎样才能仍然包含过滤器,但指定我的 SELECT 语句中的哪些列应该在 INSERT INTO 语句中使用。

非常感谢您的帮助!

【问题讨论】:

  • 只是不要选择t4.filter_col,你仍然可以在where子句中使用它。
  • 您无需将t4.filter_col 放在 SELECT 列中即可在查询中使用它。

标签: sql postgresql select sql-insert


【解决方案1】:

您必须在 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';

注意:您不必选择您在连接或过滤中使用的所有列

【讨论】:

    【解决方案2】:

    几乎是对的,但是您选择的一列太多了。试试这个:

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

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 2011-07-12
      • 1970-01-01
      • 2023-02-09
      • 2014-04-23
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多