ThinkPHP database operation aggregation query, time query, advanced query
The following tutorial column will introduce you to the aggregation query, time query, and advanced query of ThinkPHP database operations. I hope it will be helpful to friends in need! Aggregation query
In applications, we often use some statistical data, such as all current users (or those who meet certain conditions) number, the maximum points of all users, the average score of users, etc. ThinkPHP provides a series of built-in methods for these statistical operations, including:
Usage example: Get the number of users:
Db::table('think_user')->count(); // 助手函数 db('user')->count();
Or according to field statistics:
Db::table('think_user')->count('id'); // 助手函数 db('user')->count('id');
Get the maximum points of users:
Db::table('think_user')->max('score'); // 助手函数 db('user')->max('score');
Get the minimum points of users whose points are greater than 0:
Db::table('think_user')->where('score>0')->min('score'); // 助手函数 db('user')->where('score>0')->min('score');
Get the user’s average points:
Db::table('think_user')->avg('score'); // 助手函数 db('user')->avg('score');
Statistics on the user’s total score:
Db::table('think_user')->sum('score'); // 助手函数 db('user')->sum('score');Time query
Time comparison
##Use where method where
The method supports time comparison, for example: // 大于某个时间
where('create_time','> time','2016-1-1');
// 小于某个时间
where('create_time','
The third parameter can be passed in any valid time expression, and your time field type will be automatically recognized. Supported time types include timestamps, datetime, date and int.
Use the whereTime method
The whereTime method provides quick query for date and time fields, the example is as follows: // 大于某个时间
db('user') ->whereTime('birthday', '>=', '1970-10-1') ->select();
// 小于某个时间
db('user') ->whereTime('birthday', 'select();
// 时间区间查询
db('user') ->whereTime('birthday', 'between', ['1970-10-1', '2000-10-1']) ->select();
// 不在某个时间区间
db('user') ->whereTime('birthday', 'not between', ['1970-10-1', '2000-10-1']) ->select();
Time expression
also provides more convenient time expression query, for example: // 获取今天的博客
db('blog') ->whereTime('create_time', 'today') ->select();
// 获取昨天的博客
db('blog') ->whereTime('create_time', 'yesterday') ->select();
// 获取本周的博客
db('blog') ->whereTime('create_time', 'week') ->select();
// 获取上周的博客
db('blog') ->whereTime('create_time', 'last week') ->select();
// 获取本月的博客
db('blog') ->whereTime('create_time', 'month') ->select();
// 获取上月的博客
db('blog') ->whereTime('create_time', 'last month') ->select();
// 获取今年的博客
db('blog') ->whereTime('create_time', 'year') ->select();
// 获取去年的博客
db('blog') ->whereTime('create_time', 'last year') ->select();
If you query the time of the day, this week, this month and this year, it can also be simplified to:
// 获取今天的博客 db('blog') ->whereTime('create_time', 'd') ->select(); // 获取本周的博客 db('blog') ->whereTime('create_time', 'w') ->select(); // 获取本月的博客 db('blog') ->whereTime('create_time', 'm') ->select(); // 获取今年的博客 db('blog') ->whereTime('create_time', 'y') ->select();Starting from version V5.0.5, you can also use the following method to query the time
// 查询两个小时内的博客 db('blog') ->whereTime('create_time','2 hours') ->select();
Advanced query
Quick query
Quick query method isA simplified way of writing the same query conditions in multiple fields
, which can further simplify the writing of query conditions. Use | to separate multiple fields to represent OR queries. Use & to separate AND query, you can implement the following query, for example:Db::table('think_user') ->where('name|title','like','thinkphp%') ->where('create_time&update_time','>',0) ->find();The generated query SQL is:
SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' OR `title` LIKE 'thinkphp%') AND ( `create_time` > 0 AND `update_time` > 0 ) LIMIT 1Quick query supports all query expressions.
Interval query
Interval query isA kind of multiple queries for the same field Simplified way of writing the query condition
, for example:Db::table('think_user') ->where('name',['like','thinkphp%'],['like','%thinkphp']) ->where('id',['>',0],['',10],'or') ->find();The generated SQL statement is:
SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' AND `name` LIKE '%thinkphp') AND ( `id` > 0 OR `id` 10 ) LIMIT 1The query condition of the interval query must be defined in an array, and all query expression.
The following query method is wrong:
Db::table('think_user') ->where('name',['like','thinkphp%'],['like','%thinkphp']) ->where('id',5,['',10],'or') ->find();
Batch query
You can define batch conditional queries with multiple conditions, for example: Db::table('think_user'->'name' => ['like','thinkphp%'],
'title' => ['like','%thinkphp'],
'id' => ['>',0],
'status'=> 1->
The generated SQL statement is:
SELECT * FROM `think_user` WHERE `name` LIKE 'thinkphp%' AND `title` LIKE '%thinkphp' AND `id` > 0 AND `status` = '1'
Closure Query
Db::table('think_user')->select(function($query){ $query->where('name','thinkphp') ->whereOr('id','>',10);
});
The generated SQL statement is: SELECT * FROM `think_user` WHERE `name` = 'thinkphp' OR `id` > 10
Use Query object to query
$query = new \think\db\Query;$query->name('user') ->where('name','like','%think%') ->where('id','>',10) ->limit(10); Db::select($query);
If a Query object is used, any chain operations called before the select method will be invalid.
Mixed query
You can combine all the methods mentioned above to perform mixed query, for example:Db::table('think_user') ->where('name',['like','thinkphp%'],['like','%thinkphp']) ->where(function($query){ $query->where('id',['',100],'or');
}) ->select();
The generated SQL statement is:
SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' AND `name` LIKE '%thinkphp') AND ( `id` 100 )
String condition query
For some practical Complex queries can also be queried directly using native SQL statements, for example: Db::table('think_user') ->where('id > 0 AND name LIKE "thinkphp%"') ->select();
For safety reasons, we can use parameter binding for string query conditions, for example:
Db::table('think_user') ->where('id > :id AND name LIKE :name ',['id'=>0, 'name'=>'thinkphp%']) ->select();V5. Starting from 0.4, ThinkPHP supports calling query conditions multiple times on the same field, for example:
Db::table('think_user') ->where('name','like','%think%') ->where('name','like','%php%') ->where('id','in',[1,5,80,50]) ->where('id','>',10) ->find();Shortcut method (V5.0.5)
V5.0.5 version has added a series of shortcut methods to simplify queries, including:
The above is the detailed content of ThinkPHP database operation aggregation query, time query, advanced query. For more information, please follow other related articles on the PHP Chinese website!

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version