【问题标题】:Yii - complex queries using createCommand() & IF()Yii - 使用 createCommand() 和 IF() 的复杂查询
【发布时间】:2014-04-16 11:25:10
【问题描述】:

我正在尝试使用 Yii 'queryBuilder' 来构建复杂的 SQL 查询 - 现有查询如下所示:

    $cmd->select('SUM(redeemedCodes.school_points) AS reportingTotalPoints, redeemedCodes.date_redeemed, redeemedCodes.inactive, redeemedCodes.subject_id);
    $cmd->from('redeemed_codes redeemedCodes');

谁能解释如何修改 SELECT 以包含 IF 元素,如下所示: IF(orderProduct.subject_message_link = 1 AND orderProduct.message != '', CONCAT(subject.subject_name, ' ', orderProduct.message), subject.subject_name) AS reportingSubjectName')

这甚至可以在 Yii 中使用 createCommand() 吗?

我正在尝试构建类似于以下的查询:

SELECT redeemedCodes.user_id AS user_id, SUM(redeemedCodes.school_points) AS reportingTotalPoints, 
IF(orderProduct.subject_message_link = 1 AND orderProduct.message != '', CONCAT(subject.subject_name, ' ', orderProduct.message), subject.subject_name) AS reportingSubjectName 
FROM `redeemed_codes` `redeemedCodes`

【问题讨论】:

    标签: mysql database yii frameworks query-builder


    【解决方案1】:

    未测试:

    我认为 CDbExpression 可能很方便。

    $exp = new CDbExpression("IF(orderProduct.subject_message_link = 1 AND orderProduct.message != '', CONCAT(subject.subject_name, ' ', orderProduct.message), subject.subject_name)");
    

    并在需要放置字符串的任何地方使用 $exp。例如

    $sql = "Select *, " . $exp . " as ReportingSubjectName FROM ....";
    

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      $sql = "SELECT redeemedCodes.user_id AS user_id, SUM(redeemedCodes.school_points) AS reportingTotalPoints,         redeemedCodes.date_redeemed, redeemedCodes.inactive, redeemedCodes.subject_id, IF(orderProduct.subject_message_link = 1 AND orderProduct.message != '', CONCAT(subject.subject_name, ' ', orderProduct.message), subject.subject_name) AS reportingSubjectName FROM `redeemed_codes` `redeemedCodes`";
      
      $result = Yii::app()->db->createCommand($sql)->queryAll();
      

      【讨论】:

      • 不幸的是,由于特定模块的设计,我需要使用 createCommand(),因为它在代码中进一步使用了 mergeWith() 功能,因此您的方法将不起作用,但感谢您的努力
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多