是否可以使用结果"列"来自同一查询中另一个if条件的if条件?我想一次获取所有文档相关数据。
SELECT d.id, d.filename,
IF(d.document_valid_until_further_notice = 0,
IF(d.document_valid_until = "0000-00-00",
DATE_ADD(d.document_date, INTERVAL 12 MONTH),
d.document_valid_until
), "0000-00-00"
) AS calculated_valid_until_date,
IF(calculated_valid_until_date != "0000-00-00",
DATE_SUB(calculated_valid_until_date, INTERVAL 8 WEEK,
"0000-00-00"
) AS calculated_alert_expiring_date,
IF(calculated_valid_until_date > CURDATE() AND calculated_valid_until_date != "0000-00-00", 1, 0) AS expired FROM documents AS d WHERE 1 ORDER BY d.document_date DESC';
现在," calculated_valid_until_date"正确地出来,例如, 2015-10-20,但我不能在以下if语句中使用该值。有没有@ -sign。 (@calculated_valid_until_date)。有没有办法或者我必须使用单独的查询或在客户端进行此操作?
感谢您的任何想法!
答案 0 :(得分:0)
将计算出的字段包装到派生表中,然后在此派生表的外部选择中引用这些计算以继续计算:
SELECT x.id, x.filename,
x.calculated_valid_until_date,
x.calculated_alert_expiring_date,
-- Use the derived table to do the second round of calculations
IF(x.calculated_valid_until_date > CURDATE()
AND x.calculated_valid_until_date != "0000-00-00", 1, 0) AS expired
FROM
-- Project the first round of calculations into a derived table
(SELECT
d.id, d.filename, d.document_date,
IF(d.document_valid_until = '0000-00-00', DATE_ADD(d.document_date, INTERVAL 12 MONTH),
d.document_valid_until) AS calculated_valid_until_date,
IF(d.calculated_valid_until_date != '0000-00-00',
DATE_SUB(d.calculated_valid_until_date, INTERVAL 8 WEEK),
'0000-00-00') AS calculated_alert_expiring_date
FROM documents AS d
) x
WHERE 1 = 1
ORDER BY x.document_date DESC;
答案 1 :(得分:0)
SELECT x.id, x.filename,
x.calculated_valid_until_date,
IF(x.calculated_valid_until_date < CURDATE() AND x.calculated_valid_until_date != "0000-00-00", 1, 0) AS expired, IF(x.calculated_valid_until_date != '0000-00-00',
DATE_SUB(x.calculated_valid_until_date, INTERVAL 8 WEEK), '0000-00-00') AS calculated_alert_expiring_date
FROM
(SELECT
d.id, d.filename, d.document_date, d.calculated_alert_expiring_date,
IF(d.document_valid_until = '0000-00-00', DATE_ADD(d.document_date, INTERVAL 12 MONTH),
d.document_valid_until) AS calculated_valid_until_date
FROM documents AS d
) x
WHERE 1 = 1
ORDER BY x.document_date DESC
CREATE TABLE文档 ( id INT, filename VARCHAR(50), document_valid_until_further_notice TINYINT(1), document_valid_until_date日期, document_date DATE, document_valid_until日期, calculated_valid_until_date日期, calculated_alert_expiring_date日期 );
这就是我的工作方式。我没有第一次看到小提琴,所以我没有意识到我必须为&#34; calculated_valid_until_date&#34;创建表格列。和&#34; calculated_alert_expiring_date&#34;。
但无论如何,它现在正在发挥作用。谢谢!