我无法使用Yii创建以下查询:
SELECT recipientId as broadcasterId, SUM(quantity) as quantity FROM `creditlog` WHERE websiteId=3 AND timeAdded>='2013-01-17' AND timeAdded<='2013-02-17' AND recipientId IN (10000024, 10000026, 1000028) GROUP BY `recipientId`
我试过了:
$command = Yii::app()->db->createCommand(); $command->select('recipientId as broadcasterId, SUM(quantity) as quantity'); $command->from('creditlog'); $command->where('websiteId=:websiteId AND timeAdded>=:dateStart AND timeAdded<=:dateEnd AND recipientId IN (:recipients)',array(':websiteId' => $websiteId, ':dateStart' => $dateStart, ':dateEnd' => $dateEnd, ':recipients' => $broadcasterIds)); $command->group('recipientId');
而且andWhere()文档中的功能似乎丢失了。
andWhere()
问题是IN条件,但是我找不到重写它的方法。
由于您无权访问andWhere,这会使工作变得更加简单,因此您必须where像这样表达参数:
andWhere
where
$command->where(array( array('and', 'websiteId=:websiteId', array('and', 'timeAdded>=:dateStart', array('and', // ... ), $parameters);
这样做是为了使您可以在某个时候使用正确的array('in', 'recipientId', $values)语法来生成IN(...)SQL。
array('in', 'recipientId', $values)
IN(...)
然而,这是丑陋的并且难以管理。只要将所有条件简单地结合在一起,AND您就可以像这样更合理的数据表示形式以编程方式构造数据结构(实际上,这是缺少的变通方法andWhere):
AND
$conditions = array( 'websiteId=:websiteId', 'timeAdded>=:dateStart', 'timeAdded<=:dateEnd', array('in', 'recipientId', $broadcasterIds), ); $where = null; foreach ($conditions as $condition) { if (!$where) { $where = $condition; } else { $where = array('and', $where, $condition); } } $command->where($where, $parameters);
有关为何必须使用这种表达方式的更多信息,请参考的文档CDbCommand::where。
CDbCommand::where