Php Laravel在单个子句中使用多个where和sum
在我的数据库中,我有Php Laravel在单个子句中使用多个where和sum,php,laravel,laravel-5.6,Php,Laravel,Laravel 5.6,在我的数据库中,我有instagram\u actions\u histories表,其中有action\u type列,在该列中我有不同的数据,如1或2或3 我试图得到这个表数据的关系,并对存储在列中的值求和,例如 $userAddedPagesList = auth()->user()->instagramPages()->with([ 'history' => function ($query) { $query->s
instagram\u actions\u histories
表,其中有action\u type
列,在该列中我有不同的数据,如1
或2
或3
我试图得到这个表数据的关系,并对存储在列中的值求和,例如
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select(['action_type as count'])->whereActionType(1)->sum('action_type');
}
]
)->get();
顺便说一句,这个代码是不正确的,因为我想得到所有历史
,其中包含多个总和
whereActionType(1)->sum('action_type')
whereActionType(2)->sum('action_type')
whereActionType(3)->sum('action_type')
例如(pesudo代码):
更新:
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select('*')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '1');
}, 'like')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '2');
}, 'follow')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '3');
}, 'followBack');
}
]
)->get();
Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select *, (select SUM(action_type) where `action_type` = 1) as `like`, (select SUM(action_type) where `action_type` = 2) as `follow`, (select SUM(action_type) where `action_type` = 3) as `followBack` from `instagram_actions_histories` where `instagram_actions_histories`.`account_id` in (1, 2, 3))
错误:
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select('*')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '1');
}, 'like')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '2');
}, 'follow')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '3');
}, 'followBack');
}
]
)->get();
Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select *, (select SUM(action_type) where `action_type` = 1) as `like`, (select SUM(action_type) where `action_type` = 2) as `follow`, (select SUM(action_type) where `action_type` = 3) as `followBack` from `instagram_actions_histories` where `instagram_actions_histories`.`account_id` in (1, 2, 3))
如何实现此解决方案
更新:
InstagramAccount类:
class InstagramAccount extends Model
{
...
public function schedule()
{
return $this->hasOne(ScheduleInstagramAccounts::class, 'account_id');
}
public function history()
{
return $this->hasMany(InstagramActionsHistory::class, 'account_id');
}
}
class InstagramActionsHistory extends Model
{
protected $guarded=['id'];
public function page(){
return $this->belongsTo(InstagramAccount::class);
}
}
class User extends Authenticatable
{
use Notifiable;
...
public function instagramPages()
{
return $this->hasMany(InstagramAccount::class);
}
}
InstagramActionsHistory类:
class InstagramAccount extends Model
{
...
public function schedule()
{
return $this->hasOne(ScheduleInstagramAccounts::class, 'account_id');
}
public function history()
{
return $this->hasMany(InstagramActionsHistory::class, 'account_id');
}
}
class InstagramActionsHistory extends Model
{
protected $guarded=['id'];
public function page(){
return $this->belongsTo(InstagramAccount::class);
}
}
class User extends Authenticatable
{
use Notifiable;
...
public function instagramPages()
{
return $this->hasMany(InstagramAccount::class);
}
}
用户类:
class InstagramAccount extends Model
{
...
public function schedule()
{
return $this->hasOne(ScheduleInstagramAccounts::class, 'account_id');
}
public function history()
{
return $this->hasMany(InstagramActionsHistory::class, 'account_id');
}
}
class InstagramActionsHistory extends Model
{
protected $guarded=['id'];
public function page(){
return $this->belongsTo(InstagramAccount::class);
}
}
class User extends Authenticatable
{
use Notifiable;
...
public function instagramPages()
{
return $this->hasMany(InstagramAccount::class);
}
}
selectSub()
创建您在其中使用聚合(SUM
)的子查询,但select()
是一个定标器,它返回一个定标器结果;除非使用分组,否则不允许在同一级别将聚合与scaler查询混合。如果要返回每个用户的结果,请尝试添加groupBy
,这里我假设id
是users
表上的主键
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select('*')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '1');
}, 'like')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '2');
}, 'follow')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '3');
}, 'followBack');
$query->groupBy('users.id'); //<-- add this
}
]
)->get();
$userAddedPagesList=auth()->user()->instagramPages()->带([
“历史记录”=>函数($query){
$query->select(“*”)
->selectSub(函数($query){
return$query->selectRaw('SUM(操作类型)'
->其中('action_type','=','1');
},“像”)
->selectSub(函数($query){
return$query->selectRaw('SUM(操作类型)'
->式中('action_type','=','2');
}(“跟随”)
->selectSub(函数($query){
return$query->selectRaw('SUM(操作类型)'
->式中('action_type','=','3');
}“后继”);
$query->groupBy('users.id');//get();
另一种为不同类型的操作获取条件和的方法,您可以在InstagramAccount
模型中定义hasOne()
关系,如
public function history_sum()
{
return $this->hasOne(InstagramActionsHistory::class, 'account_id')
->select('account_id',
DB::raw('sum(case when action_type = 1 then 0 END) as `like`'),
DB::raw('sum(case when action_type = 2 then 0 END) as `follow`'),
DB::raw('sum(case when action_type = 3 then 0 END) as `followBack`')
)->groupBy('account_id');
}
然后,您可以按以下方式加载相关数据:
$userAddedPagesList = auth()->user()->instagramPages()->with('history_sum')->get();
使用这种方法只需执行一个额外的查询,就可以根据您的条件得到3个不同的求和结果
select `account_id`,
sum(case when action_type = 1 then action_type else 0 END) as `like`,
sum(case when action_type = 2 then action_type else 0 END) as `follow`,
sum(case when action_type = 3 then action_type else 0 END) as `followBack`
from `instagram_actions_histories`
where `instagram_actions_histories`.`account_id` in (?, ?, ?)
group by `account_id`
与其他方法(这也是一个有效答案)相比,使用withCount
将为每个操作类型添加3个相关子查询,这可能会导致性能开销,生成的查询如下所示
select `instagram_account`.*,
(select sum(action_type) from `instagram_actions_histories` where `instagram_account`.`id` = `instagram_actions_histories`.`account_id` and `action_type` = ?) as `like`,
(select sum(action_type) from `instagram_actions_histories` where `instagram_account`.`id` = `instagram_actions_histories`.`account_id` and `action_type` = ?) as `follow`,
(select sum(action_type) from `instagram_actions_histories` where `instagram_account`.`id` = `instagram_actions_histories`.`account_id` and `action_type` = ?) as `followBack`
from `instagram_account`
where `instagram_account`.`user_id` = ?
and `instagram_account`.`user_id` is not null
要检查生成的查询,请参考您需要的原始查询如下:选择操作类型,计数(*)从您的表组中,按操作类型?@koalaok我需要对操作类型求和,当值为1时求和,当值为2时求和,然后在值为3时求和,我可能会丢失一些其他信息……但这对我来说越来越奇怪。看起来您想要对所有内有相同值的记录求和……通常是计数……或者如果您真的这样做了需要count()*值的总和,然后使用sum():从instagram\u actions\u histories组中选择action\u type,sum(action\u type)按action\u type排序Avel是正确的您正在将聚合子查询
selectSub()
与普通定标器结果SELECT('*')混合使用
。您希望每个用户的结果与各自的总和同时出现吗?@Viney如果我理解您的意思,对于每个操作类型的每个具有内部关系的表,其总和更大
关系表是instagram\u actions\u histories
而不是user
,事实上我正在instagram\u a中尝试对操作类型
进行总和actions\u histories
当我将您的分组方式更改为$query->groupBy('instagram\u actions\u histories.id')
时,我会收到以下错误:SQLSTATE[42000]:语法错误或访问冲突:1055“instacheeta.instagram\u actions\u histories.account\u id”不在GROUP BY
ohh.我建议发布所有涉及的表结构。@M Khalid Junaid您的帖子是我学习新方法的原因,谢谢