我有如下表格。
id created_at grand_total amount_due
我想根据现有数据显示tendays
列中的金额。
if(SELECT DATEDIFF(NOW(),created_at)) >=0 and SELECT DATEDIFF(NOW(),created_at) <= 10
then
grand_total - amount_due as tendays
这怎么可能。
答案 0 :(得分:1)
您可以使用CASE statement或IF() function。您还可以使用BETWEEN条件来避免代码重复。我会将查询编写如下:
SELECT
id,
created_at,
grand_total,
amount_due,
CASE WHEN DATEDIFF(NOW(),created_at) BETWEEN 0 AND 10
THEN grand_total - amount_due
ELSE NULL
END as tendays
FROM some_table;
请注意,您需要为ELSE子句中不满足条件的情况定义值。但是,如果它是NULL(就像我的例子中那样),你也可以省略ELSE子句,因为NULL是默认的“值”。
使用IF()可能是:
IF(DATEDIFF(NOW(),created_at) BETWEEN 0 AND 10, grand_total - amount_due, NULL) as tendays