【问题标题】:How to find the smallest difference between two columns in Mysql?如何找到Mysql中两列之间的最小差异?
【发布时间】:2016-06-19 00:20:07
【问题描述】:

我的数据库中有一个表,其中包含用于记录人与人之间游戏的数据。我想要一个查询,它会返回两个玩家之间最接近的游戏,即记录的两个分数之间的最小差异,无论谁赢了。我已经从这样的查询开始,但我无法完全得到我想要的。

SELECT recorder_score, opponent_score 
from games 
where recorder_id = $recorder_id 
order by (recorder_score - opponent_score) 
limit 1

上面显然只会返回提交游戏的人赢得的最接近的游戏,但正如我所提到的,无论谁获胜,我都想要最接近的游戏。最好的方法是什么?

【问题讨论】:

  • 录音机总是赢家吗?对方的id是什么?请提供您的表架构、示例数据和预期结果。
  • 录音机并不总是赢家。不记录对手 ID,因为对手可能是未在站点内注册的人。识别对手的唯一方法是输入可能会有所不同的名称。该查询唯一相关的列是我提到的:recorder_id、recorder_score、ocerty_score。其他列包括 game_date、game_id 和对手名称。

标签: mysql sql


【解决方案1】:

Order by 中使用ABS 以获得两个玩家之间最接近的游戏

SELECT recorder_score, opponent_score 
from games 
where recorder_id = $recorder_id 
order by ABS(recorder_score - opponent_score) 
limit 1

【讨论】:

  • 这很完美!我完全忘记了使用 ABS,感谢您的快速响应!
猜你喜欢
  • 1970-01-01
  • 2017-04-18
  • 2015-11-12
  • 2013-10-09
  • 2021-06-27
  • 2021-03-22
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多