亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在沒有二次選擇的情況下對平均函數結果應用 where 條件?

如何在沒有二次選擇的情況下對平均函數結果應用 where 條件?

PHP
牛魔王的故事 2022-09-03 16:24:03
我有一個Laravel 6應用程序。我想用雄辯的方式只收集那些敬業度得分等于true的員工。問題是,如何在函數結果上應用子句而不在 Eloqunt 中進行第二次選擇?例如,像這樣:whereavgSELECT    `employees`.*,    AVG(responses.text_answer) > 4.6 AS engagedFROM    `employees`INNER JOIN `responses` AS `responses`ON    `responses`.`employee_id` = `employees`.`id`INNER JOIN `survey_questions` AS `surveyQuestions`ON    `surveyQuestions`.`id` = `responses`.`survey_question_id`INNER JOIN `questions` AS `questions`ON    `questions`.`id` = `surveyQuestions`.`question_id`WHERE    engaged = 1 AND `questions`.`question_type_id` = '6S'GROUP BY    `employees`.`id`但問題是這里的WHERE條件無法識別,MySQL顯示:engaged“where 子句”中的“已參與”列未知我雄辯的一部分陳述是這樣的:public function engaged()    {        return $this->relatedToMany(QuestionType::class, function(Builder $query){            if(!$this->joined($query, 'responses')){                $query->join(                    'responses AS responses',                    'responses.employee_id',                    '=',                    'employees.id',                    'inner'                );            }            if(!$this->joined($query, 'survey_questions')){                $query->join(                    'survey_questions AS surveyQuestions',                    'surveyQuestions.id',                    '=',                    'responses.survey_question_id',                    'inner'                );            }            if(!$this->joined($query, 'questions')){                $query->join(                    'questions AS questions',                    'questions.id',                    '=',                    'surveyQuestions.question_id',                    'inner'                );            }            $query->where('questions.question_type_id', '6S');            $query->select('employees.*', \DB::raw('AVG(`responses`.`text_answer`) >= 4.6 AS `engaged`'));            $query->groupBy('employees.id');        });    }
查看完整描述

1 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

不能將條件應用于聚合函數。數據庫首先計算子句,然后聚合。WHEREWHERE


相反,您可以對此使用子句(在子句之后計算)。HAVINGGROUP BY


因此,您需要更改以下內容:


WHERE 

    engaged = 1 AND `questions`.`question_type_id` = '6S'

GROUP BY

    `employees`.`id`

自:


WHERE 

    `questions`.`question_type_id` = '6S'

GROUP BY

    `employees`.`id`

HAVING

    engaged = 1

在Lavare中,這應該看起來像這樣:


$query->where('questions.question_type_id', '6S');

$query->select('employees.*', \DB::raw('AVG(`responses`.`text_answer`) >= 4.6 AS `engaged`'));

$query->groupBy('employees.id');

$query->havingRaw('engaged = 1');


查看完整回答
反對 回復 2022-09-03
  • 1 回答
  • 0 關注
  • 78 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號