如何在Update查询中使用临时变量?

时间:2017-09-04 11:44:25

标签: mysql sql

如何在执行Update语句时设置变量?

我似乎无法弄清楚语法。我使用此@tp变量来保存计算结果,它将在when条件中使用。

我想要这样的事情:

UPDATE users IU
INNER JOIN activity_stats DAS
    ON (IU.user_id=DAS.for_user_id), set
    @tp:= IU.total_subscription_time - (unix_timestamp()- IU.start_date),
    IU.time_period_left = CASE WHEN @tp > 0 THEN @tp ELSE 0 END,
    IU.used_time = (unix_timestamp() - IU.start_date),
    IU.status = CASE WHEN @tp > 0 THEN 'A' ELSE 'I' END,
    DAS.total_time_used = DAS.total_time_used + IU.used_time 
WHERE IU.time_period_left > 0
  AND IU.status='A'

但它说法语错误: but it's saying the syntax is wrong

1 个答案:

答案 0 :(得分:0)

你能试试吗?

  UPDATE users IU
INNER JOIN activity_stats DAS
    ON (IU.user_id=DAS.for_user_id), 
    IU.time_period_left = CASE WHEN (IU.total_subscription_time - (unix_timestamp()- IU.start_date)) > 0 THEN 
                        (IU.total_subscription_time - (unix_timestamp()- IU.start_date))  ELSE 0 END,
    IU.used_time = (unix_timestamp() - IU.start_date),
    IU.status = CASE WHEN (IU.total_subscription_time - (unix_timestamp()- IU.start_date)) > 0 THEN 'A' ELSE 'I' END,
    DAS.total_time_used = DAS.total_time_used + IU.used_time 
WHERE IU.time_period_left > 0
  AND IU.status='A'