一个人命中最大的幸运,莫过于在他人生中途,即在他年富力强时发现了自己生活的使命。
本文实例讲述了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框架的PHP程序设计有所帮助。
到此这篇关于ThinkPHP5联合(关联)查询、多条件查询与聚合查询实例详解就介绍到这了。人生不售来回票,一旦动身,绝不能复返。更多相关ThinkPHP5联合(关联)查询、多条件查询与聚合查询实例详解内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!