我有一个在大型表上运行的查询,所以我需要它尽可能优化运行,并希望清理这个特定的等式。
SET points = IF(
(20 - ABS(pick.guessed_rank - team.rank)) < 0,
0,
(20 - ABS(pick.guessed_rank - team.rank))
)
如何改进此功能以将ABS(pick.guess_rank - team.rank)
保存到变量中,以便我的更新看起来更像:
@diff = ABS(pick.guess_rank - team.rank;
SET points = IF(@diff < 0, 0, @diff);
或许有一种比使用if语句更好的解决方案,但在这种情况下如何使用变量的示例仍然会有所帮助。
答案 0 :(得分:0)
你想要GREATEST
函数在逻辑上做同样的事情:
SET @points = GREATEST(20 - ABS(pick.guessed_rank - team.rank), 0);
或更具体地说
SET @diff = 20 - ABS(pick.guessed_rank - team.rank);
SET @points = GREATEST(@diff,0);
并获得额外奖励积分
SET @min_margin=20;
SET @diff = ABS(pick.guessed_rank - team.rank);
SET @points_diff = GREATEST(@diff,@min_margin);
---编辑---
在直接SQL CLI中,我必须对每个变量使用@
。我认为stored procedure