在我的数据库中,我有一个名为“fine”的表,在该表中我有三个字段,issue_date、expiry_date 和 fine_amount。我希望从发行日期计算 expiry_date。过期日期应该总是比 issue_date 多 20 天,所以我将查询写为:
ALTER TABLE fine ADD
expiry_date AS DATE_ADD(CURRENT_DATE,INTERVAL 20 DAY)
但是有一个语法错误。我似乎无法找到解决方案。
我还希望 fine_amount 为 10 *(如果当前日期超过到期日期,则当前日期和到期日期之间的天数差异)。我该怎么做?
最佳答案
您无法使用计算列实现精细逻辑,因为公式涉及不确定的当前时间。来自MySQL documentation :
Literals, deterministic built-in functions, and operators are permitted. A function is deterministic if, given the same data in tables, multiple invocations produce the same result, independently of the connected user. Examples of functions that fail this definition: CONNECTION_ID(), CURRENT_USER(), NOW().
因此,您最好的选择可能是在您实际选择时只计算这些列的值。例如:
SELECT issue_date,
DATE_ADD(issue_date, INTERVAL 20 DAY) AS expiry_date,
CASE WHEN NOW() > DATE_ADD(issue_date, INTERVAL 20 DAY)
THEN 10*DATEDIFF(NOW(), DATE_ADD(issue_date, INTERVAL 20 DAY))
ELSE 0 END AS fine_amount
FROM fine
关于mysql - 无法在 SQL 中使用 date_add 创建计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42394721/