我有两个表日志和学生在日志中我想选择stud_id' s' in'和' out'在status_log中,状态为" 0"。如果stud_id进入和退出,则学生中的penalty_count正在增加。
日志
| stud_id | date_log | time_log | ampm |status_log |status |
+---------+-----------+----------+------+-----------+-------+
| 123 |2015-08-19 | 07:38:34 | am | in | 0 |
| 123 |2015-08-19 | 07:40:34 | am | out | 0 |
| 5656 |2015-08-19 | 07:45:34 | am | in | 0 |
| 5656 |2015-08-19 | 07:47:34 | am | out | 0 |
| 56577 |2015-08-19 | 07:55:34 | am | in | 0 |
| 56577 |2015-08-19 | 07:59:34 | am | out | 1 |
如果学生进出的状态为" 0"则罚款将增加1。在状态。 日志
|cardcode | name | year |section |penalty_count |
+---------+-----------+------+-----------+--------------+
| 123 |martin | 1st | A | 0 |
| 5656 |neptali | 1st | A | 0 |
| 56577 |juan | 1st | A | 0 |
请帮助我thankyuo。
答案 0 :(得分:1)
试试这样:
UPDATE student
SET penalty=penalty + 1
WHERE cardcode IN (
SELECT l1.stud_id FROM log AS l1
JOIN log AS l2 ON l1.stud_id=l2.stud_id AND l2.status_log = 'out' AND l2.status = 0
WHERE l1.status_log = 'in' AND l1.status = 0
GROUP BY l1.stud_id
)
答案 1 :(得分:0)
试试这个
UPDATE student SET penalty_count = (penalty_count + 1)
WHERE cardcode IN
(SELECT GROUP_CONCAT(stud_id) FROM log WHERE status_log = 'IN' AND status_log = 'OUT'
AND status = 0 GROUP BY stud_id)
答案 2 :(得分:0)
如果没有连接注释,也可以将此KEY(stud_id, status, status_log)
添加到表日志中,以获得更好的性能。
update
penalty
set
penalty_count = penalty_count + 1
where
cardcode IN(
select
stud_id
from
log
where
status = 0
group by
stud_id
having
(sum(status_log = 'in') + sum(status_log = 'out')) = 2
order by
null
)
请注意,order by null
是按功能禁用默认排序(解释输出中的filesort),因为您不需要在更新时对结果进行排序。