【问题标题】:Subquery with case in SELECT using Yii2 ActiveRecord使用 Yii2 ActiveRecord 在 SELECT 中带有大小写的子查询
【发布时间】:2019-11-23 11:18:45
【问题描述】:

是否可以在 Yii2 中将这种 SQL 转换为 ActiveRecord 查询:

SELECT a.id, 
    case length(a.id)
            when 6 then (select region_name from region where id = concat(left(a.id,2),'0000'))
            when 5 then (select region_name from region where id = concat(left(a.id,1),'0000'))
    end as prov,
    case length(a.id)
            when 6 then (select region_name from region where id = concat(left(a.id,4),'00'))
            when 5 then (select region_name from region where id = concat(left(a.id,3),'00'))
    end as kab,
   (select region_name from region where id = a.id) as kec
FROM region as a 
WHERE a.region_name LIKE '%kamb%'

【问题讨论】:

    标签: yii2


    【解决方案1】:

    绝对将其转换为查询构建

    $query = new \yii\db\Query;
    $query->from("region as a ");
    $query->select(new \yii\db\Expression("a.id, 
        case length(a.id)
                when 6 then (select region_name from region where id = concat(left(a.id,2),'0000'))
                when 5 then (select region_name from region where id = concat(left(a.id,1),'0000'))
        end as prov,
        case length(a.id)
                when 6 then (select region_name from region where id = concat(left(a.id,4),'00'))
                when 5 then (select region_name from region where id = concat(left(a.id,3),'00'))
        end as kab,
        (select region_name from region where id = a.id) as kec"));
    $query->andWhere(['like', 'a.region_name', 'kamb']);
    echo $query->createCommand()->rawSql;
    

    如果是 ActiveRecord 查询,请替换上面的选择部分

    【讨论】:

    • 感谢您的建议,我是yii2的新手,如何获取或显示查询结果
    • $query->all();对于所有记录和 $query->one() 对于单个记录
    • 我添加了$query->all(),但是当我 print_r($query) 查询结果不显示,只是yii\db\Query Object ( [select] => Array ( [0] => yii\db\Expression Object ( [expression] => a.id, case length(a.id) when 6 then (select region_name from region where id = concat(left(a.id,2),'0000')) when 5 then (select region_name from region where id = concat(left(a.id,1),'0000')) end as prov, case length(a.id) when 6 then (select region_name from region where id = concat(left(a.id,4),'00')) when 5 then (select region_name from region where id = conc...
    • 打印这一行 print_r($query->all());
    • 或 $result = $query->all();比打印结果 print_r($result)
    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多