【问题标题】:SQL: difference of 2 columns in a new columnSQL:新列中2列的差异
【发布时间】:2015-04-28 16:15:40
【问题描述】:

我有以下 SQL 表,有一个 positive 列和一个 negative 列,都是 ints。

positive    negative
----------------------
5           3
3           1
10          7

如何创建第三列,例如total 等于 positive - negative。另外,我希望每次positivenegative 列的元素更改时更新total 列。

如何在 SQL 中执行此操作?

编辑:我正在使用 MariaDB

【问题讨论】:

  • 您使用的是哪个 RDBMS?
  • 你能说得更具体点吗,例如请问SqlServer、MySql、Oracle 等?
  • 如果你真的需要这种非规范化,你可以使用触发器,尽管我怀疑它是否有意义

标签: sql mariadb calculated-columns mariasql


【解决方案1】:

如下所述使用计算列

你可以创建表格

create table table_name ( positive int, negitive int, difference as positive-negitive)

那么在创建之后,如果你输入的值是

insert into table_name values(3,2)

--无需输入第三列,称为计算列。

那么在插入差异之后,第三列“差异”中就会出现


【讨论】:

    【解决方案2】:

    使用此处解释的虚拟计算列https://mariadb.com/kb/en/mariadb/virtual-computed-columns/

    create table table1
    (
        positive   int not null,
        negative   int not null,
        difference int as (positive - negative) virtual
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 2017-03-10
      • 2012-05-28
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多