美文网首页
[MySQL场景系列之三] 加一操作

[MySQL场景系列之三] 加一操作

作者: 捉虫大师 | 来源:发表于2015-06-17 10:04 被阅读170次

前言

有时候,我们可能需要统计某个数目,比如文章的阅读数,页面的访问数目等,这时候,每次访问的时候我们得对数据表中的count字段进行“+1”的操作。

场景描述:

现有产品表product,每个产品记录有收藏次数count,收藏时+1,取消收藏时-1。

那么问题来了,这种情况使用MySQL有多少种解决方案呢?

方案1

子查询:

这里的子查询不是sql语句的嵌套,因为先select再update同时操作一张表是不允许的,比如这样就是 错的

update product set count = ((select count from product where product_id = 1)+1) where product_id = 1

那拆分成两条sql语句了,在程序的逻辑里面去依次执行,稍微懂点点就应该能写出来。

方案2

update product set count = count+1 where product_id = 1

一条语句简单粗暴搞定。

为了程序的可扩展性,我们在项目中并不提倡直接写SQL语句,而是使用ORM框架,有些ORM框架这种写法得特殊对待,不能像普通的SQL语句那样写,比如Yii的AR框架,就有这样的方法可参考:updateCounters,saveCounters

$model->saveCounters(array('count' => '1'));

番外

count减1的时候不小心减多了怎么办?那就当>0时才减1,否则为0;

  • if 类似三目运算

update product set count = (if(count>0, count-1, 0)) where product_id = 1

  • case

update product set count = case when count > 0 then count-1 else 0 end where product_id = 1

相关文章

网友评论

      本文标题:[MySQL场景系列之三] 加一操作

      本文链接:https://www.haomeiwen.com/subject/xrlsqttx.html