您现在的位置: 破洛洛 >> 建站学院 >> 网站开发 >> PHP教程 >> PHP综合教程 >> 正文

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

作者:佚名 来源:三连 更新时间:2017-11-15
分享到

本文实例讲述了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();


转载请注明:破洛洛(谢谢合作)
网友评论: