gpt4 book ai didi

MySQL:将字段默认值设置为其他列

转载 作者:IT老高 更新时间:2023-10-28 23:46:00 24 4
gpt4 key购买 nike

如何将字段的默认值设置为 MySQL 中的其他列?

我在Oracle中用虚拟字段做过,但我不知道如何在MySQL中做。

这是我的 table :

CREATE TABLE TSM_TRANSACTION_TBL
(
TRANS_ID INT primary key auto_increment,
LOCATION_ID INT,
TRANS_DATE DATE,
RESOURCE_ID INT,
TS_ID INT,
MAX_VALUE INT,
BOOKED_UNITS INT default 0,
REMAINING INT default MAX_VALUE - BOOKED_UNITS,
BOOKED INT not null,
USER_ID INT,
TRANS_TIME TIMESTAMP
);

最佳答案

Data Type Default Values 中所述:

The DEFAULT <strong><em>value</em></strong> clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column. See Section 11.3.5, “Automatic Initialization and Updating for TIMESTAMP.

相反,您可以定义一个插入触发器:

CREATE TRIGGER foo BEFORE INSERT ON TSM_TRANSACTION_TBL FOR EACH ROW
IF NEW.REMAINING IS NULL THEN
SET NEW.REMAINING := NEW.MAX_VALUE - NEW.BOOKED_UNITS;
END IF;;

关于MySQL:将字段默认值设置为其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15384429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com