我试图更新一列以进行日期几乎是实际日期的记录培训,这个选择正常:
SELECT MIN(training_id) AS training_id, date FROM training_terms WHERE
date > CURRENT_DATE GROUP BY training_id
它为每次培训提取最接近的日期,我想更新列"可见性"在这个选择中,所以我尝试写这样的语句:
UPDATE training_terms SET visible='1' IN (SELECT MIN(training_id)
AS training_id, date FROM training_terms WHERE date > CURRENT_DATE GROUP BY training_id);
但是那个错误出现在控制台(Linux)中:
You can't specify target table 'training_terms' for update in FROM clause
答案 0 :(得分:1)
在FROM
中使用UPDATE
是错误的。
请改为尝试:
UPDATE training_terms
SET visible='1'
WHERE training_id IN
(SELECT training_id FROM (SELECT training_id, MIN(Abs(date - CURRENT_DATE))
FROM training_terms
WHERE date > Getdate()
GROUP BY training_id) AS t);
我们使用子请求为每个ID选择日期和今天之间具有最小差异的那个(所以最接近的)
我们使用Abs()
来确保在所有情况下(未来或过去的日期)选择最接近的
答案 1 :(得分:0)
以下脚本适用于sql server。我将Current_Date更改为Getdate()
UPDATE training_terms
SET visible='1'
FROM training_terms
WHERE training_id
IN (SELECT MIN(training_id)
AS training_id FROM training_terms WHERE date > Getdate() GROUP BY training_id);