前言[随时更新]
MySQL快速复习
MySQL原生查询
选择数据表
删除数据
聚合查询
时间查询
视图查询
子查询
总结/参考
1.自增自减针对可计算的字段类型:数值型和日期时间型;
2.如对字符型字段自增,将会将该字段强行更新为自增值,如:1;
3.自增自减操作的条件,必须在该方法之前设置。

源码显示:没有更新条件时,该方法拒绝执行,确保数据安全
| 序号 | 名称 | 类型 |
|---|---|---|
| 参数1 | 字段名称 | 数值或日期时间型 |
| 参数2 | 步长值 | 整形,默认为1,可为负值 |
| 参数3 | 延时秒数 | 整形,必须正值 |
<?php
namespace app\index\controller;
use think\Db;
class Index {
public function index(){
//查询id=1010的记录
dump(Db::table('tp5_staff')->find(1010));
}
}
array(7) {
["id"] => int(1010)
["name"] => string(9) "欧阳峰"
["sex"] => int(1)
["age"] => int(18) // 年龄为 18 岁
["salary"] => float(4900)
["dept"] => int(2)
["hiredate"] => string(10) "2013-09-22"
}
<?php
namespace app\index\controller;
use think\Db;
class Index {
public function index(){
//1.更新id=1010的记录,将age 字段 加 10
Db::table('tp5_staff') -> where('id',1010) -> setInc('age',10);
//查询id=1010的记录
dump(Db::table('tp5_staff')->find(1010));
}
}
array(7) {
["id"] => int(1010)
["name"] => string(9) "欧阳峰"
["sex"] => int(1)
["age"] => int(28) //之前为18,现在已更新为28,自增成功
["salary"] => float(4900)
["dept"] => int(2)
["hiredate"] => string(10) "2013-09-22"
}


<?php
namespace app\index\controller;
use think\Db;
class Index {
public function index(){
// 1.将入职日期提前三天
Db::table('tp5_staff') -> where('id','between','1005,1007') -> setInc('hiredate',-3);
// 2.查看更新结果
dump(Db::table('tp5_staff')->where('id','between','1005,1007')->select());
}
}
array(3) {
[0] => array(7) {
["id"] => int(1005)
["name"] => string(6) "武松"
["sex"] => int(0)
["age"] => int(19)
["salary"] => float(2400)
["dept"] => int(3)
["hiredate"] => string(10) "2010-07-18" //由2010-07-21变成2010-07-18
}
[1] => array(7) {
["id"] => int(1006)
["name"] => string(9) "西门庆"
["sex"] => int(0)
["age"] => int(90)
["salary"] => float(19801)
["dept"] => int(2)
["hiredate"] => string(10) "2015-12-28" //由2015-12-31变成2015-12-28
}
[2] => array(7) {
["id"] => int(1007)
["name"] => string(9) "潘金莲"
["sex"] => int(0)
["age"] => int(39)
["salary"] => float(8567)
["dept"] => int(3)
["hiredate"] => string(10) "2016-03-17" //由2016-03-20变成2016-03-17
}
}

1.我们仅以setInc方法举例,setDec方法与之类似,不再举例;
2.通过设置自增自减步长值的正负值,这二个方法完全可以互换,上例中已体现;
3.该方法在大量数据自增自减时,效率很高,推荐使用;
4.延时更新不便演示,同学们完成可以自己完成。
db助手函数仅仅是简化了数据表的选择,其它地方都完全一样,请同学们课后自己完成,下面为例子,请仿照改写:
<?php
namespace app\index\controller;
use think\Db;
class Index {
public function index(){
//1.更新id=1010的记录,将age 字段 加 10
db('staff') -> where('id',1010) -> setInc('age',10);
//查询id=1010的记录
dump(db('staff')->find(1010));
}
}