如何使用MySQL增加字段值计数

时间:2015-08-18 07:25:46

标签: mysql laravel

我有一个学生出勤表。

字段/数据样本

id | studid | smonth | syear | total_p | total_a
1  |   20   |   08   | 2015  |   1     |   0
2  |   21   |   08   | 2015  |   0     |   1
3  |   22   |   08   | 2015  |   1     |   0

这些是第一个输入的值。然后我再次为同一个月和同一年的同一学生(20,21,22)输入值。所有都存在= 1

字段/数据样本

id | studid | smonth | syear | total_p | total_a
1  |   20   |   08   | 2015  |   2     |   0
2  |   21   |   08   | 2015  |   1     |   1
3  |   22   |   08   | 2015  |   2     |   0

我再次为同一个月和同一年的同一学生输入值。所有都存在= 1所以我想要

字段/数据样本

id | studid | smonth | syear | total_p | total_a
1  |   20   |   08   | 2015  |   3     |   0
2  |   21   |   08   | 2015  |   2     |   1
3  |   22   |   08   | 2015  |   3     |   0 

total_p值递增1的代码是什么?首先应检查前一个值然后再增加1.

我的控制器代码

$present = Input::get($student->id);
if ($present == 1)
    {
        DB::table($wys_total_attend_table)->where('studid', $student->id)
            ->where('smonth', $date_exploded[1])
            ->where('syear', $date_exploded[2])
            ->where('stotal_p', 1)
            ->update(array(
                'stotal_p' => 1 + 1,
            ));
        DB::table($wys_total_attend_table)->where('studid', $student->id)
            ->where('smonth', $date_exploded[1])
            ->where('syear', $date_exploded[2])
            ->where('stotal_p', 0)
            ->update(array(
                'stotal_p' => 1,
                'stotal_a' => 0,
            ));
    } elseif ($present == 0)
    {
        DB::table($wys_total_attend_table)->where('studid', $student->id)
            ->where('smonth', $date_exploded[1])
            ->where('syear', $date_exploded[2])
            ->where('stotal_a', 1)
            ->update(array(
                'stotal_a' => 1 + 1,
            ));
        DB::table($wys_total_attend_table)->where('studid', $student->id)
            ->where('smonth', $date_exploded[1])
            ->where('syear', $date_exploded[2])
            ->where('stotal_a', 0)
            ->update(array(
                'stotal_a' => 1,
            ));
        DB::table($wys_total_attend_table)->where('studid', $student->id)
            ->where('smonth', $date_exploded[1])
            ->where('syear', $date_exploded[2])
            ->where('stotal_p', 1)
            ->where('stotal_a', 0)
            ->update(array(
                'stotal_a' => 0 + 1,
            ));
    }

1 个答案:

答案 0 :(得分:6)

正如oNare在对您的问题的评论中所建议的那样,最简单的解决方案似乎是使用一些SQL:

UPDATE db1.student_attendance_table 
SET total_p = total_p + 1 
WHERE studid IN (20,21,22) 
AND smonth=8 
AND syear=2015;

这有什么理由不适合你吗?