我的应用程序中有以下查询,以便在将新的拳击手添加到我的数据库时修复任何未知的拳击手ID。为了使系统中的其他查询和功能更容易,添加回合时boxer_1
ID始终小于boxer_2
ID。
以下功能似乎可以完美地更新/切换boxer_1
和boxer_2
字段,但boxer_1_weight
和boxer_2_weight
值会得到奇怪的结果,我不能找出原因?
"UPDATE bouts b1, bouts b2 SET b1.unknown_global_id = 0,
b1.winner = IF(b2.winner = -3, IF(b1.boxer_1 = 0, '" . $boxer_id . "', b1.boxer_1), IF(b2.winner = -2, IF(b1.boxer_2 = 0, '" . $boxer_id . "', b1.boxer_2), b1.winner)),
b1.boxer_1 = IF(b1.boxer_1 = 0, IF('" . $boxer_id . "' > b1.boxer_2, b1.boxer_2, '" . $boxer_id . "'), IF(b1.boxer_1 < '" . $boxer_id . "', b1.boxer_1, '" . $boxer_id . "')),
b1.boxer_2 = IF(b1.boxer_2 = 0, IF('" . $boxer_id . "' < b2.boxer_1, b2.boxer_1, '" . $boxer_id . "'), IF(b1.boxer_2 > '" . $boxer_id . "', b1.boxer_2, '" . $boxer_id . "')),
b1.boxer_1_weight = IF(b2.boxer_1 = 0, IF('" . $boxer_id . "' > b2.boxer_2, b2.boxer_2_weight, b2.boxer_1_weight), IF(b2.boxer_1 < '" . $boxer_id . "', b2.boxer_1_weight, b2.boxer_2_weight)),
b1.boxer_2_weight = IF(b2.boxer_2 = 0, IF('" . $boxer_id . "' < b2.boxer_1, b2.boxer_1_weight, b2.boxer_2_weight), IF(b2.boxer_2 > '" . $boxer_id . "', b2.boxer_2_weight, b2.boxer_1_weight))
WHERE b1.unknown_global_id = '" . (int)$global_id . "'"
boxer_1/boxer_2
字段为INT(11),boxer_1_weight/boxer_2_weight
字段为十进制(10,1)
例如,如果权重字段以权重186.5和199.7开头,则在运行查询后,它们最终都是239.8,但是拳击手ID是正确的。
答案 0 :(得分:1)
您需要一个联接条件,以避免将b1
中的所选行与b2
中的每一行进行比较。
"UPDATE bouts b1
JOIN bouts b2 ON b1.bout_id = b2.bout_id
SET b1.unknown_global_id = 0,
b1.winner = IF(b2.winner = -3, IF(b1.boxer_1 = 0, '" . $boxer_id . "', b1.boxer_1), IF(b2.winner = -2, IF(b1.boxer_2 = 0, '" . $boxer_id . "', b1.boxer_2), b1.winner)),
b1.boxer_1 = IF(b1.boxer_1 = 0, IF('" . $boxer_id . "' > b1.boxer_2, b1.boxer_2, '" . $boxer_id . "'), IF(b1.boxer_1 < '" . $boxer_id . "', b1.boxer_1, '" . $boxer_id . "')),
b1.boxer_2 = IF(b1.boxer_2 = 0, IF('" . $boxer_id . "' < b2.boxer_1, b2.boxer_1, '" . $boxer_id . "'), IF(b1.boxer_2 > '" . $boxer_id . "', b1.boxer_2, '" . $boxer_id . "')),
b1.boxer_1_weight = IF(b2.boxer_1 = 0, IF('" . $boxer_id . "' > b2.boxer_2, b2.boxer_2_weight, b2.boxer_1_weight), IF(b2.boxer_1 < '" . $boxer_id . "', b2.boxer_1_weight, b2.boxer_2_weight)),
b1.boxer_2_weight = IF(b2.boxer_2 = 0, IF('" . $boxer_id . "' < b2.boxer_1, b2.boxer_1_weight, b2.boxer_2_weight), IF(b2.boxer_2 > '" . $boxer_id . "', b2.boxer_2_weight, b2.boxer_1_weight))
WHERE b1.unknown_global_id = '" . (int)$global_id . "'"