聚合查詢

版本 功能調(diào)整
5.0.14 max和min方法增加第二個參數(shù)用于設(shè)置是否強制轉(zhuǎn)換數(shù)字

在應(yīng)用中我們經(jīng)常會用到一些統(tǒng)計數(shù)據(jù),例如當前所有(或者滿足某些條件)的用戶數(shù)、所有用戶的最大積分、用戶的平均成績等等,ThinkPHP為這些統(tǒng)計操作提供了一系列的內(nèi)置方法,包括:

方法 說明
count 統(tǒng)計數(shù)量,參數(shù)是要統(tǒng)計的字段名(可選)
max 獲取最大值,參數(shù)是要統(tǒng)計的字段名(必須)
min 獲取最小值,參數(shù)是要統(tǒng)計的字段名(必須)
avg 獲取平均值,參數(shù)是要統(tǒng)計的字段名(必須)
sum 獲取總分,參數(shù)是要統(tǒng)計的字段名(必須)

用法示例:

獲取用戶數(shù):

Db::table('think_user')->count();
// 助手函數(shù)
db('user')->count();

或者根據(jù)字段統(tǒng)計:

Db::table('think_user')->count('id');
// 助手函數(shù)
db('user')->count('id');

獲取用戶的最大積分:

Db::table('think_user')->max('score');
// 助手函數(shù)
db('user')->max('score');

獲取積分大于0的用戶的最小積分:

Db::table('think_user')->where('score>0')->min('score');
// 助手函數(shù)
db('user')->where('score>0')->min('score');

獲取用戶的平均積分:

Db::table('think_user')->avg('score');
// 助手函數(shù)
db('user')->avg('score');

統(tǒng)計用戶的總成績:

Db::table('think_user')->sum('score');
// 助手函數(shù)
db('user')->sum('score');
文檔最后更新時間:2018-04-26 09:50:46

文檔
目錄

深色
模式

切換
寬度