Home PHP Framework ThinkPHP ThinkPHP database operation aggregation query, time query, advanced query

ThinkPHP database operation aggregation query, time query, advanced query

Jan 27, 2021 pm 03:29 PM
thinkphp

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();
Copy after login

Or according to field statistics:

Db::table('think_user')->count('id');
// 助手函数
db('user')->count('id');
Copy after login

Get the maximum points of users:

Db::table('think_user')->max('score');
// 助手函数
db('user')->max('score');
Copy after login

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');
Copy after login

Get the user’s average points:

Db::table('think_user')->avg('score');
// 助手函数
db('user')->avg('score');
Copy after login

Statistics on the user’s total score:

Db::table('think_user')->sum('score');
// 助手函数
db('user')->sum('score');
Copy after login

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','<= time&#39;,&#39;2016-1-1&#39;);
// 时间区间查询
where(&#39;create_time&#39;,&#39;between time&#39;,[&#39;2015-1-1&#39;,&#39;2016-1-1&#39;]);
Copy after login
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(&#39;user&#39;)    ->whereTime('birthday', '>=', '1970-10-1')    ->select();
// 小于某个时间
db('user')    ->whereTime('birthday', '<&#39;, &#39;2000-10-1&#39;)    ->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();
Copy after login

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();
Copy after login
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();
Copy after login
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();
Copy after login

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();
Copy after login
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 1
Copy after login
 
Quick 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();
Copy after login
The generated SQL statement is:
SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' AND `name` LIKE '%thinkphp') AND ( `id` > 0 OR `id` <> 10 ) LIMIT 1
Copy after login
 
The 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();
Copy after login

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->
Copy after login
The generated SQL statement is:

SELECT * FROM `think_user` WHERE `name` LIKE 'thinkphp%' AND `title` LIKE '%thinkphp' AND `id` > 0 AND `status` = '1'
Copy after login

Closure Query

Db::table('think_user')->select(function($query){    $query->where('name','thinkphp')            ->whereOr('id','>',10);
});
Copy after login
The generated SQL statement is:
SELECT * FROM `think_user` WHERE `name` = 'thinkphp' OR `id` > 10
Copy after login
Use Query object to query

You can also encapsulate the Query object in advance and pass it in select method, for example:

$query = new \think\db\Query;$query->name('user')    ->where('name','like','%think%')    ->where('id','>',10)    ->limit(10);
Db::select($query);
Copy after login
 

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',['<&#39;,10],[&#39;>',100],'or');
    })    ->select();
Copy after login
The generated SQL statement is:

SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' AND `name` LIKE '%thinkphp') AND ( `id` < 10 or `id` > 100 )
Copy after login

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();
Copy after login
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();
Copy after login
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();
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles