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模板技术总结》。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/dd025b0d2d8b4adc8ac048f2f7a408f5.html