ThinkPHP5联合(关联)查询、多条件查询与聚合查询实例详解

时间:2022-10-15 19:31:53

本文实例讲述了ThinkPHP5联合(关联)查询、多条件查询与聚合查询。分享给大家供大家参考,具体如下:

一、联合(关联)查询

1. 项目表

?
1
2
3
4
5
6
7
8
9
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. 版本号表

?
1
2
3
4
5
6
7
8
9
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. 联合查询

?
1
2
3
4
$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:

?
1
2
3
4
5
$where=array(
  "version_name"=>$version_name,
  "project_name"=>$project_name
);
$userdata=$this->where($where)->find();

例2:

?
1
2
3
4
5
$where=array(
   "version_name"=>$version_name,
   "project_name"=>$project_name
);
$userdata=$this->where($where)->select();

例3:

?
1
2
3
4
$where=array(
  "version_id"=>$version_id
);
$version_name = model("Version")->where($where)->field("version_name")->find();

方法二:

把多个SQL查询语句作为where 参数,这样就支持大于小于这样的条件了。

?
1
2
3
4
$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函数里

?
1
2
3
4
5
6
$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 这个字段,不能返回整条记录的字段。

?
1
2
3
4
$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第一个记录。

?
1
2
3
4
5
6
$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程序设计有所帮助。

原文链接:http://blog.csdn.net/tww85/article/details/52919057