where方法时间查询
1、功能:用来进行时间比较查询where查询表达式中加上关键字:time,可用以时间比较
2、常用语法:与前面学习过的普通where查询表达式相比,在比较运算符的后台加关键字:time,表示要比较的日期时间型的值,与普通比较相区别普通语法: where( '字段','查询表达式','条件')
时间查询:where( '字段','比较运算符或关键字 time', '条件' )
1. 大于某个日期Db::table('表名') -> field('字段列表') ->where('日期类型字段','> time', '日期格式') ->select();
2. 小于某个日期Db::table('表名') -> field('字段列表') ->where('日期类型字段','<= time', '日期格式') ->select();
3. 时间区间查询(时间区间用数组表示)Db::table('表名') -> field('字段列表') ->where('日期类型字段','between time', ['起始日期','终止日期']) ->select();
3、实例演示
1.任务1:查询tp5_staff表中2015年1月1日以后入职的员工信息Index.php 控制器代码:<?php
namespace app\index\controller;
//导入数据库类
use think\Db;
class Index {
public function index(){
$result = Db::table('tp5_staff')
-> field('id,name,hiredate')
->where('hiredate','> time', '2015-01-01')
->select();
dump($result);
}
}查询结果:array(5) {
[0] => array(3) {
["id"] => int(1006)
["name"] => string(9) "西门庆"
["hiredate"] => string(10) "2015-12-25"
}
[1] => array(3) {
["id"] => int(1007)
["name"] => string(9) "潘金莲"
["hiredate"] => string(10) "2016-03-14"
}
[2] => array(3) {
["id"] => int(1008)
["name"] => string(6) "宋江"
["hiredate"] => string(10) "2015-12-31"
}
[3] => array(3) {
["id"] => int(1023)
["name"] => string(9) "段王爷"
["hiredate"] => string(10) "2015-12-31"
}
[4] => array(3) {
["id"] => int(1028)
["name"] => string(6) "方方"
["hiredate"] => string(10) "2015-12-31"
}
}对应的SQL语句:SELECT `id`,`name`,`hiredate` FROM `tp5_staff` WHERE `hiredate` > '2015-01-01'
2. 任务2:查询tp5_staff表中2015年1月1日到2016年1月1日之间入职的员工Index.php 控制器源码<?php
namespace app\index\controller;
//导入数据库类
use think\Db;
class Index {
public function index(){
$result = Db::table('tp5_staff')
-> field('id,name,hiredate')
->where('hiredate','between time', ['2015-01-01','2016-01-01'])
->select();
dump($result);
}
}查询结果:array(4) {
[0] => array(3) {
["id"] => int(1006)
["name"] => string(9) "西门庆"
["hiredate"] => string(10) "2015-12-25"
}
[1] => array(3) {
["id"] => int(1008)
["name"] => string(6) "宋江"
["hiredate"] => string(10) "2015-12-31"
}
[2] => array(3) {
["id"] => int(1023)
["name"] => string(9) "段王爷"
["hiredate"] => string(10) "2015-12-31"
}
[3] => array(3) {
["id"] => int(1028)
["name"] => string(6) "方方"
["hiredate"] => string(10) "2015-12-31"
}
}对应的SQL语句:SELECT `id`,`name`,`hiredate` FROM `tp5_staff` WHERE `hiredate` BETWEEN '2015-01-01' AND '2016-01-01'SQLPRO for MySQL 中查询结果:
4、总结:where 方法对时间字段进行查询,是最基本的操作,后面马上要学习的whereTime方法,其实质仍是where方法。