sql - 我可以在插入语句 SQL 中使用数学公式吗?
问题描述
是否有一种可能的方法可以在插入语句 中制作数学公式,例如制作 column3 = column1 * column2
create table orderdetails
(orderid number(10) not null,
productid number(10) not null,
price float(10) not null,
quantity number(3) not null,
discount float(4),
ordersize varchar2(9) not null,
color varchar (10),
totalprice float(5) not null,
constraint orderid_fr2 foreign key (orderid) references orders (order_id));
insert into orderdetails values (101,3002,320,2,null,'XL','BLACK',price * quantity);
我找到了一种方法,但它只使用更新语句,每当我尝试使用 Inert 语句进行操作时,它都会给我一个错误。我只想要一个即时方法在插入方法中执行这些公式
“此处不允许列”
insert into orderdetails values (101,3002,320,2,null,'XL','BLACK',0);
update orderdetails set totalprice = price * quantity;
提前致谢。
解决方案
您可以将计算作为select
. 像这样的东西:
insert into orderdetails (orderid, productid, price, quantity, discount, ordersize, color, totalprice)
select orderid, productid, price, quantity, discount, ordersize, color, price * quantity)
from (values (101, 3002, 320, 2, null, 'XL', 'BLACK')
) v(orderid, productid, price, quantity, discount, ordersize, color);
并非所有数据库都支持标准values
表构造函数,但都有一些方法可以创建这样的行。
也就是说,您可能只需要一个计算列。再一次,确切的语法取决于数据库,但它是这样的:
create table orderdetails (
orderid number(10) not null,
productid number(10) not null,
price float(10) not null,
quantity number(3) not null,
discount float(4),
ordersize varchar2(9) not null,
color varchar (10),
totalprice generated always as (price * quantity),
constraint orderid_fr2 foreign key (orderid) references orders (order_id)
);
然后,您甚至不会将值显式插入到表中。数据库会自动计算它(在插入或更新“存储”列或查询“虚拟”列时)。
推荐阅读
- google-apps-script - 尝试使用应用程序脚本将评论从一个谷歌工作表复制到另一个位置的工作表副本
- pycharm - 如何多次运行同一个脚本而不等待它完成
- javascript - 如何在不加载的情况下切换到 getDerivedStateToProps 未定义
- python - 我怎样才能把所有这些词都剪成一个部分?
- redirect - 如何让我的重定向与 netlify 一起使用?
- ios - Swift 包管理器不允许构建包含 `import AppKit` 的包
- sql-server - 尝试通过 SQL Server Management Studio 在 Integration Services 目录中查看标准报告的执行时出错
- javascript - 无法在 JavaScript 中为 Windows.Web.Http.HttpClient 添加超时
- c# - 如何在变换旋转时以特定角度更改变换名称?
- python-3.x - ubuntu SessionNotCreatedException 上的 Selenium webdriver Python