MySQL:是否可以在更新时对CAS进行CASE?

时间:2017-12-20 07:19:07

标签: php mysql sql-update case field

所以我可能只是忽略了一些愚蠢的简单,但实际上我试图通过PHP页面来使用CAS来更新MySQL中的UPDATE。我也运行了大量的IF语句,但似乎无法使其发挥作用。

<?php
include('config.php');
$username = $_POST['username'];
$charName = $_POST['charName'];
//ID MARKS
$idMarks = $_POST['IDmarks'];
//EXPERIENCE
$EXP = $_POST['EXP'];

$sql = "UPDATE characters 
            SET CASE 
                WHEN idMarks1 IS NULL THEN idMarks1 = '$idMarks' 
                WHEN idMarks2 IS NULL THEN idMarks2 = '$idMarks' 
                WHEN idMarks3 IS NULL THEN idMarks3 = '$idMarks' 
                WHEN idMarks4 IS NULL THEN idMarks4 = '$idMarks' 
                WHEN idMarks5 IS NULL THEN idMarks5 = '$idMarks' 
                WHEN idMarks6 IS NULL THEN idMarks6 = '$idMarks' 
                WHEN idMarks7 IS NULL THEN idMarks7 = '$idMarks' 
                WHEN idMarks8 IS NULL THEN idMarks8 = '$idMarks' 
                WHEN idMarks9 IS NULL THEN idMarks9 = '$idMarks' 
                WHEN idMarks10 IS NULL THEN idMarks10 = '$idMarks' 
                WHEN idMarks11 IS NULL THEN idMarks11 = '$idMarks' 
                WHEN idMarks12 IS NULL THEN idMarks12 = '$idMarks' 
                END

                totalEXP =  totalEXP + '$EXP', 
                remEXP =    remEXP + '$EXP'

            WHERE charName = '$charName' AND username = '$username';
        ";

if ($conn->query($sql) === TRUE) {
header("Location: ../lead.php");
} else {
    echo "Error updating record: " . $conn->error;
}
?>

这里的想法是更新会将新值($ idMarks)放在它找到的第一个空值中,然后滚动到下一个EXP列。由于我之前遇到的问题,我不能使用数组,重点是idMarks列有流动性,跟踪伤口,伤口愈合疤痕或跛行,纹身是永久性的等等,这就是为什么它们是可调节的在另一页上。有没有人对如何解决这个问题有任何想法?

1 个答案:

答案 0 :(得分:0)

你有PHP,为什么要在SQL中做怪癖?

$error = false;
for($i=1; $i<12; $i++) {
    $sql = "UPDATE characters  SET idMarks$i = '$idMarks'"
        . " WHERE idMarks$i IS NULL AND charName = '$charName' AND username = '$username';";
    $sql2 = "UPDATE characters SET totalEXP =  totalEXP + '$EXP', remEXP =    remEXP + '$EXP'"
        . " WHERE charName = '$charName' AND username = '$username';";

    if ($conn->query($sql) !== TRUE) {
        $error = 'Failed with 1';
        break;
    } else if ($conn->query($sql2) !== TRUE) {
        $error = 'Failed with 2';
        break;
    }
}

 if (empty($error))
     header("Location: ../lead.php");

我会跳过“你从哪里得到那个可怕的数据库计划”这个问题,但是那个问题应该是“我想在一个请求中做出所有”优化性能“不合理的问题。

对于具有编号列的方案,SQL性能不佳。 Normalization是第一位的,只有在极少数情况下才会需要非规范化。