【问题标题】:Calculated MySQL result计算出的 MySQL 结果
【发布时间】:2020-02-14 23:07:57
【问题描述】:

我有一个 MMA 战士及其战斗的数据库,存储在两个表中:fighterfight

我想用给定的 figer id 查询数据库并在如下行中得到结果:

Result | Record | Weight| Opponent| Opponent Record | Opponent Weight | Method | Date | Round | Time

最后 4 列非常简单,但其他列很棘手,因为我不知道给定的战斗机 id 是 fighter1 还是 fighter2:

结果应取自 fight.winner,其值为“fighter1”、“fighter2”、“TBD”、“D”或“NC”。结果需要根据给定的战斗机 id 是 fighter1 还是 fighter2 来计算,因此它显示“W”、“L”、“TBD”、“D”或“NC”。

记录对手记录应取自fight.fighter1_record_after_resultfight.fighter2_record_after_result,取决于是否给定的战斗机 id 是 fighter1 或 fighter2。

WeightOpponent Weight 应取自 fight.fighter1_weightfight.fighter2_weight,具体取决于是否给定的战斗机 id 是 fighter1 或 fighter2。

对手应该取自fighter.name。谁应该被视为对手,取决于给定的战斗机 id 是 fighter1 还是 fighter2。

DB Fiddle 的数据结构和示例数据:https://www.db-fiddle.com/f/5LjJqEM6yMYuShZybcsrJ5/0

【问题讨论】:

  • 请仅将数据添加为文本,并且总是赞赏 dbfiddle 示例
  • 谢谢!我不知道 DB Fiddle。请参阅更新问题中的链接。

标签: mysql sql join calculation


【解决方案1】:

union all 在这里可能会派上用场:我们可以组合两个查询的结果集,而不是在单个查询中实现复杂的条件逻辑,在fighter1fighter2 列中搜索目标战斗机:

select
    case t.winner
        when 'fighter1' then 'W'
        when 'fighter2' then 'L'
        else t.winner
    end result,
    t.fighter1_record_after_result record,
    t.fighter1_weight weight,
    r.name opponent,
    t.fighter2_record_after_result oppononed_record,
    t.fighter2_weight opponent_weight,
    t.method,
    t.date,
    t.round,
    t.time
from fight t
left join fighter r on r.id = t.fighter2
where t.fighter1 = 64
union all
select
    case t.winner
        when 'fighter2' then 'W'
        when 'fighter1' then 'L'
        else t.winner
    end,
    t.fighter2_record_after_result,
    t.fighter2_weight,
    r.name,
    t.fighter1_record_after_result,
    t.fighter1_weight,
    t.method,
    t.date,
    t.round,
    t.time
from fight t
left join fighter r on r.id = t.fighter1
where t.fighter2 = 64

这两个参数都应该是您为其生成报告的战斗机的值。

【讨论】:

  • 此查询是否需要我为 fighter1 和 fighter2 提供一个 id?我只能提供一个战士 ID。请参阅我更新的问题中的 DB fiddle 链接。非常感谢!
  • @RawlandHustle:是的,查询只需要一名战士的 id(但它在查询中出现两次)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
相关资源
最近更新 更多