我仍在使用Yii 1.xx中的CDbCriteria的全部功能 - 我有一个相当复杂的SQL查询,我希望使用CDbCriteria格式转换为模型中的查询(如果这可能更复杂查询。
我最初的尝试......
$criteria = new CDbCriteria;
$criteria->select = array(
't.classroom_id, title',
'COALESCE(COUNT(DISTINCT r.redeemed_code_id),0) AS totalRewards',
'COALESCE(COUNT(DISTINCT ocm.user_id),0) AS totalStudents',
'COALESCE(SUM(r.points),0) AS totalPoints'
);
有人可以使用以下查询建议最好的方法吗?建议任何建议,谢谢..
SELECT
t.classroom_id,
title,
COALESCE ( r.classRewards, 0 ) AS totalRewards,
COALESCE ( r.classPoints, 0) AS totalPoints,
COALESCE ( COUNT(DISTINCT ocm.user_id), 0 ) AS totalStudents
FROM
organisation_classrooms t
LEFT JOIN ( select crc.classroom_id,
COUNT( DISTINCT crc.redeemed_code_id ) AS classRewards,
SUM( crc.points ) as classPoints
from classroom_redeemed_codes crc
JOIN organisation_classrooms t
ON crc.classroom_id = t.classroom_id
AND t.organisation_id = 37383
where crc.inactive = 0
AND ( crc.date_redeemed >= 1393286400
OR crc.date_redeemed = 0 )
group by crc.classroom_id ) r
ON t.classroom_id = r.classroom_id
LEFT OUTER JOIN organisation_classrooms_myusers ocm
ON t.classroom_id = ocm.classroom_id
WHERE
t.organisation_id = 37383
GROUP BY title
ORDER BY t.classroom_id ASC
LIMIT 10
答案 0 :(得分:4)
它不漂亮,但你要求它:D
$criteria = new CDbCriteria();
$criteria->select = '
t.classroom_id,
title,
COALESCE ( r.classRewards, 0 ) AS totalRewards,
COALESCE ( r.classPoints, 0) AS totalPoints,
COALESCE ( COUNT(DISTINCT ocm.user_id), 0 ) AS totalStudents';
$criteria->join = '
LEFT JOIN ( select crc.classroom_id,
COUNT( DISTINCT crc.redeemed_code_id ) AS classRewards,
SUM( crc.points ) as classPoints
from classroom_redeemed_codes crc
JOIN organisation_classrooms t
ON crc.classroom_id = t.classroom_id
AND t.organisation_id = 37383
where crc.inactive = 0
AND ( crc.date_redeemed >= 1393286400
OR crc.date_redeemed = 0 )
group by crc.classroom_id ) r
ON t.classroom_id = r.classroom_id
LEFT OUTER JOIN organisation_classrooms_myusers ocm
ON t.classroom_id = ocm.classroom_id
';
$criteria->group = 'title';
$criteria->order = 't.classroom_id ASC';
$criteria->limit = 10;
$criteria->addCondition('t.organisation_id = :id');
$criteria->params[':id'] = 37383;
然后:
// I will assume that model class name is OrganisationClassrooms
$models = OrganisationClassrooms::model()->findAll($criteria);
// or use it with a dataprovider
$dataProvider= new CActiveDataProvider('OrganisationClassrooms' , array(
'criteria' => $criteria,
))
答案 1 :(得分:2)
我建议您为此创建存储过程,以便轻松处理此查询。 例如。 -
$sql = Yii::app()->db->createCommand("CALL sp_getstudentdetails(:organisation_id, :date_redeemed)");
$row = $sql->queryAll(array(':organisation_id' => $organisation_id, ':date_redeemed' => date_redeemed));