php - Yii:如何使用 CDbCriteria 在 GROUP BY 之前进行 ORDER BY?

标签 php mysql group-by yii sql-order-by

像这样的查询:

SELECT * FROM (
    SELECT * FROM message ORDER BY added_on DESC
) as m WHERE receiver_id = 2 GROUP BY sender_id ORDER BY priority_id DESC;

我知道如何使用 findAllBySql 来做到这一点:

$this->findAllBySql(
    'SELECT * FROM (
        SELECT * FROM message ORDER BY added_on DESC
     ) as m WHERE receiver_id = :receiverId 
     GROUP BY sender_id 
     ORDER BY priority_id DESC', 
     array('receiverId' => $userId));

但我想知道是否有任何方法可以使用 CDbCriteria 来做到这一点导致以下代码当然不起作用:

$criteria = new CDbCriteria();
$criteria->condition = 'receiver_id = :receiverId';
$criteria->group = 'sender_id';
$criteria->order = 'priority_id DESC, added_on DESC';
$criteria->params = array('receiverId' => $userId);

谢谢。

最佳答案

我知道为时已晚。我有类似的问题,我尝试这样处理

$criteria = new CDbCriteria();
$criteria->select = '*, MAX(added_on) max_added_on';
$criteria->condition = 'receiver_id = :receiverId';
$criteria->group = 'sender_id';
$criteria->order = 'priority_id DESC, max_added_on DESC';
$criteria->params = array('receiverId' => $userId);

它解决了我的问题。如果你想检索 max_added_on,你只需要在模型类上添加另一个属性。

关于php - Yii:如何使用 CDbCriteria 在 GROUP BY 之前进行 ORDER BY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9939275/

相关文章:

MySQL查询结果: What does the time shown mean?

带有 "group by with cube"和 NULL 值的 SQL 查询

python - 迭代分组数据框中的组

python - 要合并的大文件。如何防止 Pandas 合并中的重复项?

php - 为什么输入的[]没有提交?

php - HTML5 输入时间从 24 小时到 12 小时

php - 是否需要验证 $_GET id

php - 如何摆脱 PHP 通知 : Undefined index: HTTPS in X on line 123

javascript - 如何存储脚本代码(示例: Google analytics) to database and show in the textarea? 类似于wordpress

mysql - 使用mysql从UTC格式计算特定月份