ThinkPHP5联合(关联)查询、多条件查询与聚合查询实例详解
本文实例讲述了ThinkPHP5联合(关联)查询、多条件查询与聚合查询。分享给大家供大家参考,具体如下:
一、联合(关联)查询
1. 项目表
DROP TABLE IF EXISTS `darling_project`; CREATE TABLE `darling_project` ( `project_id` int(32) NOT NULL AUTO_INCREMENT, `project_name` varchar(20) NOT NULL, `create_time` int(32) NOT NULL, PRIMARY KEY (`project_id`), UNIQUE KEY `project_id` (`project_id`), UNIQUE KEY `project_name` (`project_name`) );
2. 版本号表
DROP TABLE IF EXISTS `darling_version`; CREATE TABLE `darling_version` ( `version_id` int(32) NOT NULL AUTO_INCREMENT, `project_id` int(32) NOT NULL, `version_name` varchar(128) NOT NULL, `create_time` int(32) NOT NULL, PRIMARY KEY (version_id), UNIQUE KEY `version_id` (`version_id`) );
3. 联合查询
$where=array( "version_id"=>$_POST['version_id'] ); $Project_version = model('Project')->join("darling_version","darling_version.project_id = darling_project.project_id")->where($where)->find();
二、多条件查询
方法一:
把查询条件放到数组里作为where函数参数,但是如果有大于小于这样的条件参数,数组里是无法赋值的。
例1:
$where=array( "version_name"=>$version_name, "project_name"=>$project_name ); $userdata=$this->where($where)->find();
例2:
$where=array( "version_name"=>$version_name, "project_name"=>$project_name ); $userdata=$this->where($where)->select();
例3:
$where=array( "version_id"=>$version_id ); $version_name = model("Version")->where($where)->field("version_name")->find();
方法二:
把多个SQL查询语句作为where 参数,这样就支持大于小于这样的条件了。
$package = model('admin/Package') ->where("project_id=".$Project_version['project_id']." and version_id=".$Project_version['version_id']." and status>1") ->order('create_time desc') ->find();
方法三:
把SQL查询语句放到多个where函数里
$package = model('admin/Package') ->where("project_id=".$Project_version['project_id']) ->where("version_id=".$Project_version['version_id']) ->where("status>1") ->order('create_time desc') ->find();
三、聚合max 函数
1. 如下可以返还最新插入的升级包,但是只会返还create_time 这个字段,不能返回整条记录的字段。
$package = model('admin/Package') ->where("project_id=".$Project_version['project_id']) ->where("version_id=".$Project_version['version_id']) ->where("status>1")->max(create_time)
2. 所以可以使用下面这个达到找出最新插入的记录并返还整条记录字段,先做order 排序,再find第一个记录。
$package = model('admin/Package') ->where("project_id=".$Project_version['project_id']) ->where("version_id=".$Project_version['version_id']) ->where("status>1") ->order('create_time desc') ->find();
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。
相关推荐
K先生 2020-11-10
wushengyong 2020-10-28
FellowYourHeart 2020-10-05
YClimb 2020-09-15
gaosf 2020-06-14
Hesland 2020-06-14
fanfangood 2020-06-14
稳哥的小灶 2020-05-29
小周 2020-04-30
gaosf 2020-04-25
小周 2020-04-25
FellowYourHeart 2020-04-25
稳哥的小灶 2020-04-25
FellowYourHeart 2020-04-23
ThinkPHP 2020-03-28
doupoo 2020-01-28