我在主查询中有一个子查询,如下所示:
$subquery = (new Query())->select('COUNT(project_sup_id)')
->from('project_supervisors AS sup')
->where(['AND','sup.project_ref_id = p.project_id']);
$uQuery =(new Query())->select(['project_id','supcount' => $subquery])
->from('projects AS p')
->join('LEFT JOIN','project_supervisors AS sup','sup.project_ref_id = project_id')
->andWhere('IF(supcount>0, sup_project_status=1, project_status=1)');
我正在尝试根据逻辑写出条件,即,如果从子查询获得的计数大于零,那么条件必须是sup_project_status=1
其他project_status=1
。在普通的Mysql中,如果条件在哪里,很容易写,但是在yii2我不理解如何写。
答案 0 :(得分:0)
尝试将yii \ db \ Expression用于RDBMS本机表达式:
->andWhere(new yii\db\Expression('IF(supcount>0, sup_project_status=1, project_status=1)'));
您可以使用以下方法检查SQL:
echo $uQuery->createCommand()->getRawSql();
它返回Query对象准备好的SQL命令。您也可以将整个SQL编写为yii \ db \ Command:
$count = Yii::$app->db->createCommand('SELECT count(...) FROM ... WHERE ...')->queryScalar();