【问题标题】:New to sql, how to insert column values into new column?sql新手,如何将列值插入新列?
【发布时间】:2013-05-16 17:25:17
【问题描述】:

我有什么:

ALTER TABLE countryb
ADD gnppercap real
;


INSERT INTO countryb (gnppercap)
    SELECT gnp/population
    FROM countryb
;

我成功创建了“gnppercap”列,现在我想用变量填充每一行的值。新变量是 gnp 和 1/population 的乘积,变量 gnp 和 population 已经在我正在更改的表中,countryb。

这是错误:

ERROR: null value in column "code" violates not-null constraint
SQL state: 23502
Detail: Failing row contains (null, null, null, null, null, null, null, null, null, null, null, >null, null, null, null, 0.000263028).

我知道表 countryb 中有大量的非空变量,所以我认为这就是那些空值。我以为既然我指定了要插入值的列,那没关系...?

我迷路了。帮助表示赞赏!

【问题讨论】:

  • 您添加了一列。它得到了它应该得到的任何默认值。现在您要更改现有行中的此值。
  • 因此现在使用“更新”是有意义的。谢谢

标签: sql postgresql insert insert-select


【解决方案1】:

您想要更新表格,而不是插入新行。

update countryb set gnppercap = gnp/population

顺便说一句:您可能不想将计算值存储在单独的列中。如果更新 gnp 或人口会发生什么?您的 gnppercap 列将不准确。

【讨论】:

  • 哇,这太容易了,不敢相信我错过了。另一个问题,有时分子和分母中的值为0,我想将它们设置为null。我该怎么做?
  • 这会给你一个空的gnppercap。默认情况下,您的新列可能为 null,因此无需将该值重新更新为 null。我会这样做: update countryb set gnppercap = gnp/population where gnp 0 and population 0
猜你喜欢
  • 2021-11-24
  • 1970-01-01
  • 2021-12-15
  • 2017-08-10
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
相关资源
最近更新 更多